我如何组合数组的项目?

Mar*_* AJ 0 php for-loop

这是我的代码:

$arr = [
    0 => [1, 2, 3, 4],
    1 => ['one', 'two', 'three', 'four'] 
    ];

$res = [];    
foreach ($arr as $item){
    foreach($item as $i){
        $res = [$i, $item];
    }
}

print_r($res);

/*
Array
(
    [0] => four
    [1] => Array
        (
            [0] => one
            [1] => two
            [2] => three
            [3] => four
        )

)
Run Code Online (Sandbox Code Playgroud)

如你所见,结果没有任何意义.这是预期的结果:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
        )
    [1] => Array
        (
            [0] => 2
            [1] => two
        )
    [2] => Array
        (
            [0] => 3
            [1] => three
        )
    [3] => Array
        (
            [0] => 4
            [1] => four
        )
)
Run Code Online (Sandbox Code Playgroud)

你知道,嵌套循环总是让我感到困惑.无论如何,有谁知道我如何达到预期的结果?

Yos*_*shi 8

更新:

或者,如Shafizadeh所述,简单地说:

<?php
$arr = [
    [1, 2, 3, 4],
    ['one', 'two', 'three', 'four']
];

$out = array_map(null, ...$arr);
Run Code Online (Sandbox Code Playgroud)

这个?

<?php
$arr = [
    [1, 2, 3, 4],
    ['one', 'two', 'three', 'four']
];

// array_map accepts an open number of input arrays and applies
// a given callback on each *set* of *i-th* values from these arrays.
// The return value of the callback will be the new array value
// of the final array:
                            // get all function arguments as an array
$out = array_map(function (...$r) {
    return $r;
}, ...$arr); // *spread* input array as individual input arguments

print_r($out);

// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => one
//         )
// 
//     [1] => Array
//         (
//             [0] => 2
//             [1] => two
//         )
// ...
Run Code Online (Sandbox Code Playgroud)

演示:https://3v4l.org/uJNKG

参考:http://php.net/manual/functions.arguments.php#functions.variable-arg-list.new

  • [*PHP RFC:Argument Unpacking*](https://wiki.php.net/rfc/argument_unpacking) (2认同)