将PHP数组合并到另一个数组的多维数组中

时间:2017-10-18 12:04:09

标签: php arrays

我有3个阵列

Array(
[0] => 0.123
[1] => 0.221)

Array(
[0] => abcd
[1] => defg)

Array(
[0] => 10000
[1] => 20000)

是否可以添加密钥并将其合并为此格式的多维数组?

Array(
[0] => Array(
     [si] => 0.123
     [ri] => abcd
     [pr] => 10000)
[1] = > Array(
     [si] => 0,221
     [ri] => defg
     [pr] => 20000)

1 个答案:

答案 0 :(得分:1)

使用array_maparray_combine函数的简短解决方案:

$arr1 = [ 0.123, 0.221 ];
$arr2 = [ 'abcd', 'defg' ];
$arr3 = [ 10000, 20000 ];

$result = array_map(function($v){
    return array_combine(['si', 'ri', 'pr'], $v);
}, array_map(null, $arr1, $arr2, $arr3));

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [si] => 0.123
            [ri] => abcd
            [pr] => 10000
        )

    [1] => Array
        (
            [si] => 0.221
            [ri] => defg
            [pr] => 20000
        )
)

http://php.net/manual/en/function.array-map.php