Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Php中将附加字段推送到数组中?_Php_Arrays_Loops_Foreach - Fatal编程技术网

如何在Php中将附加字段推送到数组中?

如何在Php中将附加字段推送到数组中?,php,arrays,loops,foreach,Php,Arrays,Loops,Foreach,您好,我正在寻找使用php将附加字段推入数组的最佳实践。 我已经尝试了array_push及其等价的$array[]=$var;但这不是我想要的 我有一个这样的循环: foreach($lakesNearby as $lakes){ $dist = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit); $lakes['distance'] = $

您好,我正在寻找使用php将附加字段推入数组的最佳实践。 我已经尝试了array_push及其等价的$array[]=$var;但这不是我想要的

我有一个这样的循环:

    foreach($lakesNearby as $lakes){
        $dist = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
        $lakes['distance'] = $dist;
        $lakesReturned[] = $lakes;
    }
但我相信有更好的方法将最后两行合并,并将其推到附近的$lakes?

Hmmm…,可能是:

foreach($lakesNearby as &$lakes){
    $lakes['distance'] = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
}

所有数据都将在$lakesnarear数组中,您不需要另一个数组。

正如Alex在评论中所说:

为了完整起见,请参见php.net/manual/de/control-structures.foreach.php:“为了能够直接修改循环中的数组元素,请在$value之前加上&。在这种情况下,值将通过引用分配

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

+1回答问题。为了完整起见,请参阅:“为了能够直接修改循环中的数组元素,请在$value之前加上&。在这种情况下,将通过引用指定值。”