Skip to content
Advertisement

how to append a new key and value field in a multi-dimensional array in PHP?

I have an array with the following format. Example Json for reference: https://jsoneditoronline.org/#left=cloud.42c7485653ea40549da90cf4338f8b23

I want to add “super_parent_id” in each of the childData arrays. So if childData exists, i need to append super_parent_id to that child array. Similarly if a childData array exists within that array, i need to append super_parent_id to that child array.

I think recursion can solve this issue but I am not sure how to do it. Thank you.

Advertisement

Answer

Yes, correct, recursion is one of the approaches for the problem. Here is a code snippet explaining how to implement the recursive modification of such data structure.

function appendSuperParentId(&$elem, $superParentId){
    $elem["super_parent_id"] = $superParentId;
    if (isset($elem["childData"])){
        appendSuperParentId($elem["childData"], $superParentId);
    }
}

$elems = [
    [
        "name" => "xyz",
        "childData" => [
            "name" => "foo",
            "childData" => [
            ] 
        ]
    ]
];
for ($i = 0; i < count($elems); $i++){
    appendSuperParentId($elems[$i]["childData"], $superParentId);
}

not tested, but idea should work.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement