Lucas Rabello Simões Lucas Rabello Simões - 4 months ago 9
SQL Question

Loop trough an array while adding a new key:value pair based on another value

I would really appreciate some help here. I am going nuts on this.

I have the following data inside an multi level arrarray

1: id: 41, parent: null, name: lucas
2: id: 52, parent: null, name: george
3: id 98: parent: 41, name: julian
...


I need to loop trough this array and a
'childrens'
key and value to the parent while summing +1 to this value every time i run over an entry that has 'parent' not set to null.

1: id: 41, parent: null, name: lucas, children: 1


How? D:
I tried this inside a foreach

foreach($post as $parsedPost) {
if($parsedPost['parent'] > 0){
$idChild = $parsedPost['id'];
$idParent = $parsedPost['parent'];
$post[$idParent]["childrens"]++;
}
}


Of course it returns a notice because the index
['childrens']
does not exist. Also, it's adding the
childrens:value
to the first children and not to the parent.
Why? D:

Answer

Hope this helps.

$post[] = ["id" => "41", "parent" => null, "name" => "lucas"];
$post[] = ["id" => "52", "parent" => null, "name" => "george"];
$post[] = ["id" => "98", "parent" => "41", "name" => "Julian"];

foreach ($post as $parsedPost)
{
    if ($parsedPost['parent'] > 0 && $parsedPost['parent'] != "")
    {
        $idChild = $parsedPost['id'];
        $idParent = $parsedPost['parent'];
        $parentKey = array_search($idParent,array_column($post,'id'));
        if(!isset($post[$parentKey]["childrens"]))
        {
            $post[$parentKey]["childrens"] = 0;
        }
        $post[$parentKey]["childrens"]++;
    }
}
print_r($post);

Output:

Array
(
    [0] => Array
        (
            [id] => 41
            [parent] => 
            [name] => lucas
            [childrens] => 1
        )

    [1] => Array
        (
            [id] => 52
            [parent] => 
            [name] => george
        )

    [2] => Array
        (
            [id] => 98
            [parent] => 41
            [name] => Julian
        )

)