Jump to content

[SOLVED] associating values from two arrays


mapboy

Recommended Posts

I have two arrays, one is a unique identifier (not a key, but a city code), and the other is a value (distance).  I need to be able to grab the minimum distance, 2nd minimum distance, 3rd, minimum distance, etc, and retain the unique identifier associated with the distances.

 

$dist_array = array(100, 200, 137, 421);

$city_array = array(270123, 270124, 270132, 270965);

 

Each distance value corresponds with the identifier value in the order of the arrays (100 with 270123, etc).  When I grab the max value for $dist_array (421), how can I get it to associate with 270965 in $city_array?  Or, when I sort the $dist_array, how can I have the city_codes stay associated with the proper distance?

Link to comment
Share on other sites

First combine them:

$city_distances = array_combine($dist_array, $city_array);

Now you have an array like this:

array(
100 => 270123, 
200 => 270124, 
137 => 270132, 
421 => 270965
);

 

And then you can sort it like this:

arsort($city_distances);

 

But note, it will be sorted in reverse order.

Link to comment
Share on other sites

If you don't want to combine them, then just make sure when you sort your $dist_array you maintain the original key structure! Most of the core PHP sorting functions give you that option! That way you can use the keys in $dist_array to get the value from your $city_array or vice versa!

Link to comment
Share on other sites

If you don't want to combine them, then just make sure when you sort your $dist_array you maintain the original key structure! Most of the core PHP sorting functions give you that option! That way you can use the keys in $dist_array to get the value from your $city_array or vice versa!

 

I didn't believe you. but you're right :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.