我有一個foreach循環遍歷帖子並執行操作(例如爲每個設置一個$distance
變量)。通過有條件的,它需要做兩件事,它們獨立工作,但我不能讓他們一起工作。從foreach循環問題添加到多維數組
$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
}
}
謝謝,這個工作 –