array combine three or more arrays with php -


ok, assuming have 5 arrays, indexed arrays, , combine them, best way can figure, there better way 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 wend version of glass robots answer handle variable number of arrays, it's slower obviously, faster original:

function test_my_new(){     $args=func_get_args();     $keys=array_shift($args);     $vkeys=array_shift($args);     $results=array();     foreach($args $key=>$array){         $vkey=array_shift($vkeys);         foreach($array $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); 

personally readability way:

$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); $result = array();  foreach ($keys $id => $key) {     $result[$key] = array(         'name'  => $names[$id],         'email' => $emails[$id],         'id'    => $ids[$id],     ); } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -