好吧,假设我有5个数组,都是索引数组,我想把它们组合起来,这是我能想到的最好的方法,有没有更好的方法来处理这个?
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));
Run Code Online (Sandbox Code Playgroud)
这会返回:
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
)
)
Run Code Online (Sandbox Code Playgroud)
编辑:经过大量的基准测试后,我使用了一个版本的Glass Robots回答来处理可变数量的数组,它显然比他明显慢,但比我原来的更快:
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; …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
$arr = [
0 => [1, 2, 3, 4],
1 => ['one', 'two', 'three', 'four']
];
$res = [];
foreach ($arr as $item){
foreach($item as $i){
$res = [$i, $item];
}
}
print_r($res);
/*
Array
(
[0] => four
[1] => Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
)
Run Code Online (Sandbox Code Playgroud)
如你所见,结果没有任何意义.这是预期的结果:
Array
(
[0] => Array
(
[0] => 1
[1] => one
)
[1] => Array
(
[0] …Run Code Online (Sandbox Code Playgroud)