以下是my code:
$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
)
)
如你所见,结果没有任何意义。这是预期结果:
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
)
)
你知道,嵌套循环总是让我感到困惑。无论如何,是否有人知道如何达到预期的结果?
答案 0 :(得分:8)
<强>更新强>:
或者,如Shafizadeh所述,简单地说:
<?php
$arr = [
[1, 2, 3, 4],
['one', 'two', 'three', 'four']
];
$out = array_map(null, ...$arr);
此?
<?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
// )
// ...
参考:http://php.net/manual/functions.arguments.php#functions.variable-arg-list.new
答案 1 :(得分:1)
试着想象一下如果你手工做的话你会怎么做:
$i
)。$i
增加一个答案 2 :(得分:1)
您可以将array_column()
用于单个for循环。
$arr = [
0 => [1, 2, 3, 4],
1 => ['one', 'two', 'three', 'four']
];
$res = [];
foreach ($arr[0] as $key => $val){
$res[] = array_column($arr, $key);
}
以下是工作示例:https://3v4l.org/vXdvD
答案 3 :(得分:1)
使用foreach的$key => $value
语法迭代第一个子数组,将迭代索引处的元素(即$item
)与第二个子数组中的对应元素组合在一起(即$arr[1][$key]
):
foreach ($arr[0] as $key => $item) {
$res[] = [$item, $arr[1][$key] ];
}
观看演示here
我承认我从Yoshi的answer了解了spread operator - 我知道它存在于JavaScript中而不是PHP中。下面的解释开始在没有扩展运算符的情况下应用array_map(),然后应用它。
要开始应用array_map(),第一个参数是anonymous function,它返回它在单个数组中接受的两个参数。第二个和第三个参数是两个子阵列。
$arr = [
0 => [1, 2, 3, 4],
1 => ['one', 'two', 'three', 'four']
];
$res = array_map(function($item0, $item1) {
return [ $item0, $item1];
}, $arr[0], $arr[1]);
print_r($res);
参见演示here。
然后使用该代码,扩展运算符可用于替换匿名函数的参数(即$item0, $item1
)以及array_map()的第二个和第三个参数(即$arr[0], $arr[1]
)
$res = array_map(function(...$items) {
return $items;
}, ...$arr);
请参阅here的演示。
答案 4 :(得分:0)
$arr = [
0 => [1, 2, 3, 4],
1 => ['one', 'two', 'three', 'four']
];
$res = [];
foreach ($arr[0] as $key => $item) {
$res[] = [$item, $arr[1][$key] ];
}
print_r($res);