php - How to create a path based on array with multiple children
Get the solution ↓↓↓Solution:
I've had to fix the data as the levels of data don't match up. The rest of the code is new as I found so many errors from your existing code.
Comments in code...
$data = [
"name" => "Item1",
"children" =>
[[
"name" => "Item2",
"children" =>[
["name" => "Item3"],
["name" => "Item4"]]
],
["name" => "Item5"]]
];
print_r(flatten($data));
function flatten($arr, $pathSoFar = '') {
$lst = [];
$path = $pathSoFar."/";
foreach ( $arr as $key => $value ) {
if ( $key === 'name' ) {
// Add name of current level onto path
$path .= $value;
$lst[$value] = $path;
}
else if ( $key === 'children' ) {
//Process child elements recursively and add into current array
$lst = array_merge($lst, flatten($value, $path));
}
else {
// This is for sub-elements which probably are (for example) 0, 1
// (removing trailing / to stop multiples)
$lst = array_merge($lst, flatten($value, rtrim($path,"/")));
}
}
return $lst;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function store() on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.