【问题标题】:Adding to multidimensional array from foreach loop issue从 foreach 循环问题添加到多维数组
【发布时间】:2015-09-21 19:58:33
【问题描述】:

我有一个 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
  }
}

【问题讨论】:

    标签: php arrays wordpress loops foreach


    【解决方案1】:

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

    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"]);
    }
    

    【讨论】:

      【解决方案2】:

      距离应该包含在值中

      那么你为什么不直接这样做——先将$distance 放入$value,然后再将$value 放入$results 数组中?

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

      【讨论】:

      • 谢谢,我看到了逻辑,但是这段代码破坏了页面
      猜你喜欢
      • 2012-04-06
      • 2016-02-09
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 2011-05-27
      相关资源
      最近更新 更多