1

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
  }
}

2 Answers 2

4

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"]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;

1 Comment

Thanks, and I see the logic, but this code broke the page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.