从foreach循环添加到多维数组的问题


Adding to multidimensional array from foreach loop issue

我有一个foreach循环,它遍历帖子并执行操作(例如为每个帖子设置一个$distance变量(。通过一个条件,它需要做两件事,这两件事独立工作,但我无法让它们一起工作。

$results[] = $value;工作,因为它添加了数组($value(

$results['distance'] = $distance;本身工作,但我需要包括$value阵列。

如果我把它们都放在里面,它会产生两倍于应该有的数组。距离应该包含在值中。如果我做array_push,它也可以,但我需要指定密钥。

foreach ($posts as $key => $value) {
  $loop->the_post();
  $result_lat = get_post_meta( $value->ID, 'latitude', true );
  $result_long = get_post_meta( $value->ID, 'longitude', true );
  $distance = round(calc_distance($input_lat, $input_lng, $result_lat, $result_long, "M"));
  // add item to results if within distance
  if ($distance < $_GET['within']) {
    $results[] = $value;
    $results['distance'] = $distance; // add distance to array
  }
}

使用单个多维数组存储值:

foreach ($posts as $key => $value) {
    #..
    $results[$key]["values"] = $value;  
    $results[$key]["distance"] = $distance;
}
#show first row
print_r( array_values($results)[0] );
#iterate
foreach ($results as $r_key => $r_value) {
    print_r($r_value["distance"]);
}

距离应包含在值中

那么,为什么不直接这样做呢?在将$value放入$results数组之前,先将$distance放入$value

$value['distance'] = $distance;
$results[] = $value;