是的,数据可直接附在<代码>foreach(>上原始输入阵列的行文。
使用阵列结构的总体好处是能够在特定阵列中具体获取/分离数据,而无需将不需要的数据输入变量。
详细情况:
- The new element must be declared by reference (the value must be a variable prepended with
&
) -- otherwise there is no indication to modify the original array.
- If the reference variable is not later assigned a value, the default value will be
null
.
守则: (Demo
$array = [
[ foo => a , bar => 1],
[ foo => b , bar => 2],
];
foreach ($array as [ new => &$x, bar => $x]);
var_export($array);
产出:
array (
0 =>
array (
foo => a ,
bar => 1,
new => 1,
),
1 =>
array (
foo => b ,
bar => 2,
new => 2,
),
)
Using the above sample input array, a body-less loop can be used to assign the first level keys as a new column in the array without declaring the full row as a reference.
Code: (Demo)
foreach ($array as $x => [ new => &$x]);
这种办法要求宣布一个范围较小的变量与:
foreach ($array as $x => &$row) {
$row[ new ] = $x;
}
如果没有逐条修改,则使用<代码>foreach()的签字要求值变量。
foreach ($array as $x => $row) {
$array[$x][ new ] = $x;
}
产出(全部):
array (
0 =>
array (
foo => a ,
bar => 1,
new => 0,
),
1 =>
array (
foo => b ,
bar => 2,
new => 1,
),
)
http://stackoverflow.com/a/77741493/2943403” 回答是使用这一技术,并通过另一个文件将数值分配给参考变量。
@Dharman在一项PHP内提到,没有<条码>的阵列结构实施相同的行为:Demo。
$arr = [];
[ foo => &$v] = $arr;
$v = 1;
var_export($arr);
// output: array( foo => 1)