Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add children where empty in nested object?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading