Search code examples
phparraysloopsassociative-arrayarray-merge

How to take each item of array1 combine item array 2 to new array in PHP


I have a difficult situation. I will have an array like

array(
    'title' => array(
        "ABC",
        "DEF",
        "GHI"
    ),
    "url" => array(
        "abc",
        "def",
        "ghi"
    )
);

Now, I want to create new array with data like:

array(
    array(
        "title" => "ABC",
        "url" => "abc",
    ),
    array(
        "title" => "DEF",
        "url" => "def",
    ),
    array(
        "title" => "GHI",
        "url" => "ghi",
    ),
);

I did by foreach loop but in fact, I have more than 10 arrays. I will be decrease the performance if I create 10 foreach loops for each of them.

So my question is:

  • Does it have any function in PHP can do that or we have to do it by ourself?

Thank for your reading and answering.


Solution

  • This will work dynamic with any number of subarrays in your main array.
    It uses array_keys to find all the subarrays.

    $keys = array_keys($arr);
    $count = count($arr[$keys[0]]);
    
    For($i=0; $i<$count; $i++){
        Foreach($keys as $key){
            $res[$i][$key] = $arr[$key][$i];
        }
    }
    
    Var_dump($res);
    

    https://3v4l.org/41PNh

    Example with three subarrays: https://3v4l.org/5SmSW