I'm facing to a problem : I'm given a json entry which is organized like that :
Array
(
[0] => stdClass Object
(
[libelle] => Emploi
[sousLibelle] => Réhabilitation professionnelle
)
[1] => stdClass Object
(
[libelle] => Emploi
[sousLibelle] => Formations et aides à l'emploi
)
[2] => stdClass Object
(
[libelle] => Emploi
[sousLibelle] => Emploi
)
}
What I need to do is that :
Array
(
[0] => stdClass Object
(
[libelle] => Emploi
[sousLibelle][0] => Réhabilitation professionnelle
[sousLibelle][1] => Formations et aides à l'emploi
[sousLibelle][2] => Emploi
)
)
I'm a bit lost here, some help would be nice.
thank you
From what I gather, the following loop is what you wish to do.
It will create a new array with the 'libelle' value as the key, and then remove duplicates.
$new_arr = array();
foreach($array as $val) {
$new_arr[$val['libelle']][] = $val['sousLibelle'];
}
$new_arr = array_unique($new_arr);
Edit: Just a side note, json_decode
for converting the array to a PHP array from a JSON array, and json_encode
if you're producing the results back in a JSON array.
So for adding a new $key=>$value
to your $result
object, the following rules apply:
$result[$key]
does not exist yet, create it and set it to $value
.$result[$key]
exists and is an array, check if $value
is in it. If not, add it ($result[$key][] = $value
).$result[$key]
exists but is not an array, check if it is equal to $value
. If not, create a new array with the original $result[$key]
and the new value $value
and assign it.Did I get this correctly? Because the above translates quite straightforwardly into PHP. I could write it out for you, but I will leave the actual work to you :)