I have a multidimensional array with over 200 nested objects which some have children and some don’t.
I’m trying to add empty children to where leaf: false and children don’t exist.
[{
"id": "GRP-25",
"text": "Name 1",
"leaf": false,
"children": [{
"id": "APP-222",
"text": "Another name",
"leaf": true
}]
},
{
"id": "GRP-25",
"text": "Name 2",
"leaf": false,
"children": [] // <- missing, need to add empty children
}
]
function addEmptyChildren(array &$data)
{
foreach ($data as $k => $v)
{
// recursive call
if (is_array($v)) {
addEmptyChildren($data[$k]);
continue;
}
if ($data['leaf'] === false && !property_exists('children', $k)) {
$data['children'] = [];
}
}
}
addEmptyChildren($result);
>Solution :
I think I see the problem. Based on is_array(), $data['leaf'], etc., it looks like the function is meant to deal with an array of arrays, probably from json_decode($json, true), rather than an array of objects. If that’s the case, then property_exists is not the right way to check for children.
Instead of this:
if ($data['leaf'] === false && !property_exists('children', $k)) {
use isset() or array_key_exists() instead.
if ($data['leaf'] === false && !isset($data['children'])) {