...

View Full Version : sort a multidimensional array in a specific order



webdevised
06-24-2010, 08:52 PM
I am been trying to get this to work all day... I am the below array



Array
(
[0] => Array
(
[0] => TN
[1] => Darrel
)
[1] => Array
(
[0] => TN
[1] => Anderson
)
[2] => Array
(
[0] => GA
[1] => Smith
)
[3] => Array
(
[0] => NY
[1] => Porter
)
[4] => Array
(
[0] => MO
[1] => Mclean
)
[5] => Array
(
[0] => NY
[1] => Johnson
)

)


I world like to sort it in this order NY,GA,MO,TN and then in each of those order by alphabetize


this is my current code.. i might be heading the wrong way with it...


$sortorder = array('NY', 'GA', 'MO', 'TN');


// compare function
function cmpi($a)
{

global $sortorder;
$cmpa = array_search($a[0], $sortorder);

return ($cmpa) ? 1 : -1;

}

// do the array sorting
usort($latest_array, 'cmpi');


any ideas would be great...

Fou-Lu
06-24-2010, 11:41 PM
Your comparator is missing half its arguments O.o


function cmpi($a, $b)
{
global $sortorder;
$aVal = array_search($a[0], $sortorder);
$bVal = array_search($b[0], $sortorder);

$result = $aVal - $bVal;
if ($result === 0)
{
$result = strcmp($aVal[1], $bVal[1]);
}
return $result;
}

That should be what you want.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum