Search code examples
phparray-merge

Php vertically array merge


This is my php arrays:

$array['title'] = array(0 => 'John', 1 => 'Wick');
$array['price'] = array(0 => '100$', 1 => '200$');
$array['count'] = array(0 => 88900, 1 => 92000);

I want to convert it like this:

$result[0] = array('title' => 'John', 'price' => '100$', 'count' => 88900);
$result[1] = array('title' => 'Wick', 'price' => '200$', 'count' => 92000);

I will do this a big data. How is the most effective solution?


Solution

  • Maybe there a native way to do this but this works: It is the most effective way? i'll let you benchmark it.

    $array['title'] = array(0 => 'John', 1 => 'Wick');
    $array['price'] = array(0 => '100$', 1 => '200$');
    $array['count'] = array(0 => 88900, 1 => 92000);
    
    foreach($array['title'] as $k=>$v){
       $result[$k]['title']=$v;
       $result[$k]['price']=$array['price'][$k];
       $result[$k]['count']=$array['count'][$k];
    }
    
    print_r($result);
    
    > Array (
    >     [0] => Array
    >         (
    >             [title] => John
    >             [price] => 100$
    >             [count] => 88900
    >         )
    > 
    >     [1] => Array
    >         (
    >             [title] => Wick
    >             [price] => 200$
    >             [count] => 92000
    >         )
    > 
    > )