Search code examples
phparraysmultidimensional-arraypass-by-referencearray-map

How to synchronously nest subarrays from one array into subarrays of another?


I have 2 multi-dimensional arrays:

$category = array (
    37 = array (id=1, name=joe, boss=kev)
    73 = array (id=55, name=diane, boss=rox)
    11 = array (id=4, name=bideo, boss=julia)
)  

$other_variable = array (
    1 = array (
        picture1 = array (name=zee, id=4),
        picture2 = array (name=izzy, id=1)
    )
    2 = array (
        picture1 = array (name=foo, id=55),
        picture2 = array (name=ido, id=44)        
    )
    3 = array (
        picture1 = array (name=wheez, id=87),
        picture2 = array (name=ardu, id=9)
    )
)  

I want to combine them so that

$category = array (
    37 = array (
        id=1, 
        name=joe, 
        boss=kev, 
        other_variable = array (
            picture1 = array (name=zee, id=4),
            picture2 = array (name=izzy, id=1)
    ),

    73 = array (
        id=55, 
        name=diane, 
        boss=rox, 
        other_variable = array (
            picture1 = array (name=foo, id=55),
            picture2 = array (name=ido, id=44)
    ),
    11 = array (
        id=4, 
        name=bideo, 
        boss=julia, 
        other_variable = array (
            picture1 = array (name=wheez, id=87),
            picture2 = array (name=ardu, id=9)
    )
)  

I have tried

 $new_array = array_map(null, $category, $other_variable);  

That combines the two arrays, but it creates several nested levels in the array. I am looking for something much cleaner that maintains $category as the parent array.


Solution

  • Are you expecting something like this? Here we are using next and current function for incrementing internal pointer of array and getting current value.

    Try this code snippet here

    foreach($category as &$value)
    {
        $value["other_variable"]=current($other_variable);
        next($other_variable);
    }
    print_r($category);