PHP:将相同长度的数组组合成一个多维数组,两个数组都以值(而不是键)结尾? [英] PHP: combining same-length arrays into a multidimensional array where both end up as values (not keys)?
问题描述
我有两个相同长度的数组,如下所示:
I have two same-length arrays like this:
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
最后我要结束:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 3
)
)
array_combine
会将上述一组值放入数组 keys 中,我不这样做不需要-我希望两者最终都作为数组值,将两个数组的每一项组合到一个新数组中。
array_combine
would make one set of the above values into array keys, which I don't want -- I want both to end up as array values, combining each item of the two arrays into a new array.
是否有内置函数可以执行THI还是我必须自己动手?
Is there a built in function to do this or do I have to roll my own?
推荐答案
是否有内置函数可以执行此
Is there a built in function to do this
是
还是我必须自己动弹?
or do I have to roll my own?
否
通过调用 array_map()
并将其输入 null
作为回调参数,然后馈入2个或更多数组,它将根据需要重组您的数据。
By calling array_map()
and feeding it null
as the callback parameter, then feeding it 2 or more arrays, it will restructure your data as desired.
代码:(演示)
$array1 = ['a', 'b', 'c'];
$array2 = [1, 2, 3];
var_export(array_map(null, $array1, $array2));
输出:
array (
0 =>
array (
0 => 'a',
1 => 1,
),
1 =>
array (
0 => 'b',
1 => 2,
),
2 =>
array (
0 => 'c',
1 => 3,
),
)
这篇关于PHP:将相同长度的数组组合成一个多维数组,两个数组都以值(而不是键)结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!