Reputation: 3627
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
}
}
Upvotes: 1
Views: 5680
Reputation: 6276
Use a single multidimensional array to store values:
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"]);
}
Upvotes: 4
Reputation: 96339
Distance is supposed to be included in the value
Well then why don’t you just do exactly that – put $distance
into $value
, before you put $value
into the $results
array?
$value['distance'] = $distance;
$results[] = $value;
Upvotes: 0