Page 1 of 1

sorting associative array based on another

Posted: Fri Aug 28, 2009 1:08 pm
by fredsnertz
I'm trying to sort one associative array based on another. The common key is the id.

$array1[$id]=$info
$array2[$id]['occurred']=$count

I'd like array1 to be sorted based on the "occurred" count in array2 using the common key "id".

$array1 = array('53' => 'green', '107' => 'blue', '9999' => 'red');
$array2 = array('107' => ('occured' => '22'), '53' => ('occurred' => '9000'), '9999' => ('occurred' => '50'));
$array2 has other subfields that aren't relevant.

After sorting, $array1 would be
107 => blue (occurred=22)
9999 => red (occurred=50)
53 => green (occurred=9999)

I tried array_multisort but this doesn't seem to keep the indexes intact. I looked at uasort but I don't see a way to pass in the second array to the custom compare function. I guess I could make it global but there has to be something simpler that I'm missing.

Re: sorting associative array based on another

Posted: Fri Aug 28, 2009 1:40 pm
by Eran
You need to lose the nested arrays for your second array as it makes the operation more complicated and adds no more information.

Code: Select all

$array1 = array('53' => 'green', '107' => 'blue', '9999' => 'red');
$array2 = array('107' => '22', '53' => '9000', '9999' => '50'); //Without nested arrays
asort($array2);
$sorted = array();
foreach(array_keys($array2) as $key){
    $sorted[] = $array1[$key];
}