按键的顺序组合多个数组


combine multiple arrays with order of key

例如,我有超过3个不同的数组,元素如下:

1日数组

hello-1
hi-1

2数组

ok-two
hi-2
22-two
hello

第三阵列

hi-3rd
hello3

等等…

我想按顺序一个一个地组合这个数组。例如,上述3个数组的预期输出为:

hello-1 
ok-two
hi-3rd
hi-1
hi-2 
hello3 
22-two 
hello

我试过array_merge()。但是它把第二个数组附加在第一个数组之后,这不是我想要的,所以这里我有点卡住了不知道我可以用哪个函数。有什么提示或想法吗?

这应该可以为您工作:

首先将每个数组的第一个元素放入子数组,然后将第二个值放入下一个子数组,以此类推,就得到了这个数组结构:

Array
(
    [0] => Array
        (
            [0] => hello-1
            [1] => ok-two
            [2] => hi-3rd
        )
    //...
) 

在此之后,您可以使用array_walk_recursive()循环遍历每个数组值并将每个值放入数组。

<?php
    $arr1 = [
        "hello-1",
        "hi-1",
    ];
    $arr2 = [
        "ok-two",
        "hi-2",
        "22-two",
        "hello",
    ];
    $arr3 = [
        "hi-3rd",
        "hello3",
    ];
    $arr = call_user_func_array("array_map", [NULL, $arr1, $arr2, $arr3]);
    $result = [];
    array_walk_recursive($arr, function($v)use(&$result){
        if(!is_null($v))
            $result[] = $v;
    });
    print_r($result);

?>
输出:

Array
(
    [0] => hello-1
    [1] => ok-two
    [2] => hi-3rd
    [3] => hi-1
    [4] => hi-2
    [5] => hello3
    [6] => 22-two
    [7] => hello
)

我有另一种方法来解决这个问题

<?php
$arr1 = array(
        "hello-1",
        "hi-1");
$arr2 = array("ok-two",
              "hi-2",
              "22-two",
              "hello");
$arr3 = array(
    "hi-3rd",
    "hello3");
$max = count($arr1);
$max = count($arr2) > $max ? count($arr2) : $max;
$max = count($arr3) > $max ? count($arr3) : $max;
$result = array();
for ($i = 0; $i < $max; $i++) {
    if (isset($arr1[$i])) {
        $result[] = $arr1[$i];
    }
    if (isset($arr2[$i])) {
        $result[] = $arr2[$i];
    }
    if (isset($arr3[$i])) {
        $result[] = $arr3[$i];
    }
}
print_r($result);