array 用 php 组合三个或更多数组 [英] array combine three or more arrays with php
本文介绍了array 用 php 组合三个或更多数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,假设我有 5 个数组,全部都是索引数组,我想将它们组合起来,这是我能想到的最好方法,有没有更好的方法来处理这个问题?
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));
返回:
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
)
)
经过大量基准测试后,我使用了一个版本的 Glass Robots 来处理可变数量的数组,它显然比他的要慢,但比我原来的要快:
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);
推荐答案
就个人而言,我会这样做:
Personally for readability I would do it this 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 as $id => $key) {
$result[$key] = array(
'name' => $names[$id],
'email' => $emails[$id],
'id' => $ids[$id],
);
}
这篇关于array 用 php 组合三个或更多数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文