array combine three or more arrays with php

Viewed 20288

ok, assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, is there a better way to handle this?

function mymap_arrays(){
    $args=func_get_args();
    $key=array_shift($args);
    return array_combine($key,$args);
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$u_keys=array_fill(0,count($names),array('name','email','id'));
$users=array_combine($keys,array_map('mymap_arrays',$u_keys,$names,$emails,$ids));

this returns:

Array
(
    [u1] => Array
        (
            [name] => Bob
            [email] => bob@mail.com
            [id] => 1
        )

    [u2] => Array
        (
            [name] => Fred
            [email] => fred@mail.com
            [id] => 2
        )

    [u3] => Array
        (
            [name] => Joe
            [email] => joe@mail.com
            [id] => 3
        )

)

EDIT: After lots of benchmarking I wend with a version of Glass Robots answer to handle a variable number of arrays, it's slower than his obviously, but faster than my original:

function test_my_new(){
    $args=func_get_args();
    $keys=array_shift($args);
    $vkeys=array_shift($args);
    $results=array();
    foreach($args as $key=>$array){
        $vkey=array_shift($vkeys);
        foreach($array as $akey=>$val){
            $result[$keys[$akey]][$vkey]=$val;
        }
    }
    return $result;
}
$keys=array('u1','u2','u3');
$names=array('Bob','Fred','Joe');
$emails=array('bob@mail.com','fred@mail.com','joe@mail.com');
$ids=array(1,2,3);
$vkeys=array('name','email','id');
test_my_new($keys,$vkeys,$names,$emails,$ids);
4 Answers

Simply try this for multiples array combine (if you have length of arrays)

$array_id = array ('1', '2', '3');
$array1 = array ('arr1_value1', 'arr1_value2', 'arr1_value3');
$array2 = array ('arr2_value1', 'arr2_value2', 'arr2_value3');
$array3 = array ('arr3_value1', 'arr3_value2', 'arr3_value3');

  $lenght = count($array_id);
  $i = 0;

  while ($i < $lenght) {
    $result[] = array(
        $array_id[$i]
        , $array1[$i]
        , $array2[$i]
        , $array3[$i]
    );
    $i++;
  }

echo '<pre>';
print_r($result);
Related