sorting associative array based on another
Posted: Fri Aug 28, 2009 1:08 pm
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.
$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.