解构数组时,可以多次访问同一个元素值吗?

问题描述 投票:0回答:1

自 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
,该怎么办? 可以吗?

php arrays foreach variable-assignment destructuring
1个回答
6
投票

它看起来很不正统,而且有用的场景很少,但是是的,它是可能/有效的。

只需再次重复“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,
)
© www.soinside.com 2019 - 2024. All rights reserved.