phparraysmultidimensional-arrayforeachassociative-array

Building nested array with foreach


I am trying to build an associative multidimensional array like this:

array(
    [0] => Array(
        Parent => Mr Smith,
        Children => array(
            Firstmane => Bob,
            Surname => Smith,
            Age => 16,
        )
    )
    [1] => Array(
        Parent => Mr Jones,
        Children => array(
            Firstmane => Davey,
            Surname => Jones,
            Age => 15,
        )
    )
)

My current code looks like this:

foreach($Parents as $parent) {
    $opdata[] = ['Children'=>array(),'Parent'=>$name]; 
    
    foreach($children as $child) {           
        $opdata['Children'][] = [ 
            'Firstmane'=>$code, 
            'Surname'=>$cost, 
            'Age'=>$age,
        ];
    }    
}

However, This puts the ‘Children’ in a new array rather than in the child array of each parent. Like this:

array(
    [0] => Array(
        Parent => Mr Smith,
        Children => array()
    )
    [1] => Array(
        Parent => Mr Jones,
        Children => array()
    )
    Children => array(
        [0] => array(
            Firstmane => Bob,
            Surname => Smith,
            Age => 16,
        [1] => array(
            Firstmane => Davey,
            Surname => Jones,
            Age => 15,
        )
    )
)

I can’t work how to add the child arrays to the correct nested array with the correct parent.


Solution

  • First create, then assign, not the other way around. So in your case the code could look like this:

    foreach ($Parents as $parent) {
        $person = ['Parent' => $name];
        foreach ($children as $child) {           
            $person['Children'][] = ['Firstmane' => $code, 
                                     'Surname'   => $cost, 
                                     'Age'       => $age];
        }    
        $opdata[] = $person; 
    }
    

    I say: "could look", because it is unclear where a variables like $name, $code, $cost and $age are coming from. I guess it has to come from the $parent and $child variables, but they are not.

    I also tried to make the code easier to read using indentation. How you indent is up to you, but smushing everything together doesn't help readability.