自 PHP7.1 起,
foreach()
表达式可以实现数组解构,作为解包行值并进行个性化变量赋值的一种方式。
在
foreach()
循环中使用数组解构时,特定值是否可以通过其关联键多次访问?
例如:
$array = [
['group' => 'A', 'name' => 'Ann', 'age' => 19],
['group' => 'B', 'name' => 'Bea', 'age' => 26],
['group' => 'A', 'name' => 'Cam', 'age' => 32],
['group' => 'B', 'name' => 'Des', 'age' => 24]
];
我知道我可以使用:
foreach ($array as ['group' => $group, 'name' => $name, 'age' => $age]) {
// do stuff with $group, $name, and $age
}
但是,如果我想在解构时再次访问
$group
,该怎么办? 可以吗?
它看起来很不正统,而且有用的场景很少,但是是的,它是可能/有效的。
只需再次重复“key => value”语法并在值位置提供不同的变量即可。 在这种情况下,按键可能会重复。
这里演示了如何使用数组解构通过无体 foreach 循环“旋转”结果集。
代码:(演示)
$array = [
['group' => 'A', 'name' => 'Ann', 'age' => 19],
['group' => 'B', 'name' => 'Bea', 'age' => 26],
['group' => 'A', 'name' => 'Cam', 'age' => 32],
['group' => 'B', 'name' => 'Des', 'age' => 24]
];
$result = [];
foreach ($array as ['group' => $group, 'group' => $result[$group]['group'], 'name' => $name, 'age' => $result[$group][$name]]);
# assignment of group value----^^^^^^
# 1st use of group value--------------------------^^^^^^^^^^^^^^^^^^^^^^^^
# assignment of name value------------------------------------------------------------^^^^^
# 2nd use of group value and 1st use of name value----------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^
var_export($result);
输出:
array (
'A' =>
array (
'group' => 'A',
'Ann' => 19,
'Cam' => 32,
),
'B' =>
array (
'group' => 'B',
'Bea' => 26,
'Des' => 24,
),
)
按键访问不限于静态值;可以动态访问数组键:(Demo)
$array = [
['group' => 'A', 'A' => 1, 'B' => 2,],
['group' => 'B', 'A' => 3, 'B' => 4,],
['group' => 'A', 'A' => 5, 'B' => 6,],
['group' => 'B', 'A' => 7, 'B' => 8,]
];
$result = [];
foreach ($array as ['group' => $group, $group => $result[$group][]]);
var_export($result);
输出:
array (
'A' =>
array (
0 => 1,
1 => 5,
),
'B' =>
array (
0 => 4,
1 => 8,
),
)
同样的技术也适用于
foreach()
循环的上下文之外。 (演示)
['one' => $result[], 'one' => $result[]] = ['one' => 1];
var_export($result);
输出:
array (
0 => 1,
1 => 1,
)