I have a foreach loop that iterates through posts and performs actions (such as setting a $distance
variable for each). Through a conditional, it needs to do two things, which work independently but I cannot get them to work together.
$results[] = $value;
works, as it adds the array ($value
)
$results['distance'] = $distance;
works by itself but I need to include the $value
arrays.
If I have them both in, it results in twice as many arrays as there should be. Distance is supposed to be included in the value. If I do an array_push
it works also, but I need to specify the key.
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
}
}
Use a single multidimensional array to store values:
Well then why donât you just do exactly that â put
$distance
into$value
, before you put$value
into the$results
array?