在PHP中从现有的四维数组创建新的多维数组

时间:2015-02-25 10:41:50

标签: php

我有一个像:

这样的数组
$array1=array(1,2,3,4),
$array2=array("test1","test2","test3","test4"),
$array3=array("2014","2015","2014","2015"),
$array4=array("201","101","203","104")

现在我想创建一个新的多维数组$array4,其值如下:

[0]=>{"1","test1","2014","201"}
[1]=>{"2","test2","2015","101"}
[2]=>{"3","test3","2014","203"}
[3]=>{"4","test4","2015","104"}

4 个答案:

答案 0 :(得分:1)

您需要的代码在函数array_map()的文档页面中作为示例提供:

$output = array_map(NULL, $array1, $array2, $array3, $array4);

这就是全部!

答案 1 :(得分:0)

尝试此功能:

$array1=array(1,2,3,4);
$array2=array("test1","test2","test3","test4");
$array3=array("2014","2015","2014","2015");
$array4=array("201","101","203","104");

print_r(convert($array1, $array2, $array3, $array4));

function convert() {
    $newArr = [];
    $arrays = func_get_args();
    for ($i = 0; $i < count($arrays);$i++) {
        for ($k = 0; $k < count($arrays[$i]); $k++) {
            $newArr[$k][$i] = $arrays[$i][$k];
        }
    }
    return $newArr;
}

答案 2 :(得分:0)

您可以使用array_map来获得所需的结果:

$merge = function() {
    return func_get_args();
};
$result = array_map($merge, $array1, $array2, $array3, $array4);
var_dump($result)

答案 3 :(得分:0)

它似乎是函数array_column()的工作:

// Combine all the input arrays into a single 2-dimensional array
// Pass the combined array to a function that will return the list
// of its columns
$output = transpose(array($array1, $array2, $array3, $array4));


function transpose(array $array)
{
    // Store the result here
    $result = array();
    // Get each column, put it into the result
    foreach (array_keys($array[0]) as $key) {
        $result[$key] = array_column($array, $key);
    }
    return $result;
}

另一种解决方案相同但使用函数array_reduce()来遍历数组:

function transpose(array $array)
{
    return array_reduce(
        array_keys($array[0]),
        function (array $carry, $key) use ($array) {
            $carry[$key] = array_column($array, $key);
            return $carry;
        },
        array()
    );
}