I have this array:
$arr = [
["id"=>20,
"name"=>"a",
"parent"=>28,
],
["id"=>21,
"name"=>"a-child",
"parent"=>20,
],
["id"=>27,
"name"=>"a-child-b",
"parent"=>20,
],
["id"=>28,
"name"=>"A parent",
"parent"=>0,
],
["id"=>12,
"name"=>"no parent",
"parent"=>0,
]];
What I want is to group it based on parent key, where parent = id && parent > 0 or the id is the parent for this element and the element has parent, if the parent key is greater than zero.
In the above array id=12 has no parent, id=20 has child 21, 27 and it is a child for id=28.
What I did :
public function sort($arr){
$result = [];
// Get child
foreach($arr as $key => $row) {
if($row['parent'] > 0) {
$result[$row->parent][] = ['id' => $row['id'], 'name' => $row['name']];
unset($arr[$key]);
}
}
// Get parent and append child
foreach($arr as $key => $row) {
$result[$row['id']] = ['name' => $row['name'],
'child' => $result[$row['id']]];
}
return $result;
}
That problem is that, this is only for 1 level of child like parent => child array().
What I want to make is a method which gets an argument (above array), where I don't know, how many levels of nesting I will have and returns grouped by parent key array:
$arr = [
["id"=>28,
"name"=>"A parent",
"parent"=>0,
'child' => [
["id"=>20,
"name"=>"a",
"parent"=>28,
'child' => [
["id"=>21,
"name"=>"a-child",
"parent"=>20,
],
["id"=>27,
"name"=>"a-child-b",
"parent"=>20,
]
]
]
]
],
["id"=>12,
"name"=>"no parent",
"parent"=>0,
]];