Home > Mobile >  How to add children where empty in nested object?
How to add children where empty in nested object?

Time:03-04

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);

CodePudding user response:

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

CodePudding user response:

A lot more going on in your loop than appears to be necessary.


$str = '[{
    "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
}
]';
$result = json_decode($str);
if (json_last_error() !== 0){echo json_last_error_msg();}
#print_r($result);

function addEmptyChildren(array &$data)
{
    foreach ($data as $k => $v) {

        if ($v->leaf === false && !isset($v->children)) {
            $v->children = [];
        }
    }
}

addEmptyChildren($result);
echo json_encode($result, JSON_PRETTY_PRINT);

RESULT

[
    {
        "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": []
    }
]
  •  Tags:  
  • php
  • Related