解构数组时,是否可以多次访问相同的元素值?
While destructuring an array, can the same element value be accessed more than once?
自 PHP7.1 起,foreach()
表达式可以实现 array destructuring 作为一种解包行值并进行个性化变量赋值的方法。
在 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
怎么办?可能吗?
看起来很不正统,用到的场景也很少,但确实是possible/valid。
只需再次重复“key => value”语法并在值位置提供不同的变量。在这种情况下,键可能会重复。
这是使用数组解构通过 body-less foreach 循环“透视”结果集的演示。
代码:(Demo)
$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]]);
# 1st assignment of group value^^^^^^
# 2nd assignment of group value-------------------^^^^^^^^^^^^^^^^^^^^^^^^
var_export($result);
输出:
array (
'A' =>
array (
'group' => 'A',
'Ann' => 19,
'Cam' => 32,
),
'B' =>
array (
'group' => 'B',
'Bea' => 26,
'Des' => 24,
),
)
同样的技术也适用于 foreach()
循环的上下文之外。 (Demo)
['one' => $result[], 'one' => $result[]] = ['one' => 1];
var_export($result);
输出:
array (
0 => 1,
1 => 1,
)
自 PHP7.1 起,foreach()
表达式可以实现 array destructuring 作为一种解包行值并进行个性化变量赋值的方法。
在 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
怎么办?可能吗?
看起来很不正统,用到的场景也很少,但确实是possible/valid。
只需再次重复“key => value”语法并在值位置提供不同的变量。在这种情况下,键可能会重复。
这是使用数组解构通过 body-less foreach 循环“透视”结果集的演示。
代码:(Demo)
$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]]);
# 1st assignment of group value^^^^^^
# 2nd assignment of group value-------------------^^^^^^^^^^^^^^^^^^^^^^^^
var_export($result);
输出:
array (
'A' =>
array (
'group' => 'A',
'Ann' => 19,
'Cam' => 32,
),
'B' =>
array (
'group' => 'B',
'Bea' => 26,
'Des' => 24,
),
)
同样的技术也适用于 foreach()
循环的上下文之外。 (Demo)
['one' => $result[], 'one' => $result[]] = ['one' => 1];
var_export($result);
输出:
array (
0 => 1,
1 => 1,
)