I have the following(json) object:
$obj = json_decode(\'{
\"Group1\": {
\"Blue\": {
\"Round\": [
\"Harold\",
I have created simple recursive function.For your example. Store previous key values in one variable and add all data according to previous key and create new array.(which contain all previous keys as index and last element as value) . Try following code:
$obj = json_decode('{
"Group1": {
"Blue": {
"Round": [
"Harold",
"Arthur",
"Tom"
]
},
"Green": {
"Round": [
"Harold"
],
"Circle": [
"Todd",
"Mike"
]
}
},
"Group2": {
"Blue": {
"Round": [
"Peter"
]
}
}
}', true);
function traverse_array($array,$key="",$prev="",&$final_op=array())
{
if(is_array($array))
{
$prev .= $key." - ";
foreach ($array as $key => $value) {
traverse_array($value,$key,$prev,$final_op);
}
}
else
{
$prev =trim($prev," - ");
$final_op[$prev][]=$array;
}
return $final_op;
}
$data = traverse_array($obj);
foreach ($data as $key => $value) {
echo $key." (".implode(",", $value).")";
echo PHP_EOL;
}
DEMO