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?

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.

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!

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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.