php中组合数组形成多维数组
我知道有很多答案,但我似乎无法得到正确的答案。我有以下数组和我尝试过的内容:
$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );
$e = array_combine($a, array($b,$c,$d) );
但是这样我得到了错误 array_combine() [function.array-combine]: 两个参数应该具有相同数量的元素
。
我知道这是因为 $a
的数组值不是键。这就是为什么我来这里是为了看看我是否可以得到一些帮助,找到一个可以帮助我使它看起来像这样的答案:
array(2) {
[1421]=>array( [0] => teststring1
[1] => teststring3
[2] => teststring5
)
[2241]=>array( [0] => teststring2
[1] => teststring4
[2] => teststring6
)
}
I know there's a ton of answers but I can't seem to get it right. I have the following arrays and what I've tried:
$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );
$e = array_combine($a, array($b,$c,$d) );
But with this I get the error array_combine() [function.array-combine]: Both parameters should have an equal number of elements
.
I know it's because the $a
's array values aren't keys. That's why I'm coming here to see if I could get some help with an answer that can help me make it look something like this:
array(2) {
[1421]=>array( [0] => teststring1
[1] => teststring3
[2] => teststring5
)
[2241]=>array( [0] => teststring2
[1] => teststring4
[2] => teststring6
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您可以控制创建数组,则应该像这样创建它们:
如果没有,则必须循环它们:
DEMO
If you have control over creating the arrays, you should create them like:
If not, you have to loop over them:
DEMO
这是函数式编码风格的一行代码。调用
array_map()
一个null
函数参数后跟“values”数组将生成所需的子数组结构。array_combine()
进行 key=>value 关联。代码(演示)
输出:
超级干净,对吧?我知道。当您无法控制初始数组生成步骤时,这是一个有用的小技巧。
Here is a one-liner in a functional coding style. Calling
array_map()
with anull
function parameter followed by the "values" arrays will generate the desired subarray structures.array_combine()
does the key=>value associations.Code (Demo)
Output:
Super clean, right? I know. It's a useful little trick when you don't have control of the initial array generation step.
这是 array_merge_recursive 的新版本,它将处理整数键。让知道进展如何。
Here's a new version of array_merge_recursive which will handle integer keys. Let know how it goes.