Good morning, given the below data structure (in JSON for ease of reading)
[
{
\"parent\": \"root\",
\"active\": \"1\",
\"label\": \"Index\",
Not very hard:
function flatten(array $array) {
$branch = [];
foreach ($array as $item) {
$children = [];
if (isset($item['children']) && is_array($item['children'])) {
$children = flatten($item['children']);
unset($item['children']);
}
$branch = array_merge($branch, [$item], $children);
}
return $branch;
}
Easy-peasy
function flatten($items, &$r) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : null;
unset($item->children);
$r []= $item;
if($c)
flatten($c, $r);
}
}
flatten(json_decode($json), $r);
print_r($r);
This accumulates results in one single buffer, passed by reference. This is far more efficient than building a whole new array on each iteration, which is basically a variation of the Shlemiel the painter's algorithm.
If you prefer functional approach, you can use generators:
function flatten($items) {
foreach($items as $item) {
$c = isset($item->children) ? $item->children : [];
unset($item->children);
yield $item;
foreach(flatten($c) as $child)
yield $child;
}
}
foreach(flatten(json_decode($json)) as $item)
print_r($item);