PDA

View Full Version : How can I sort a multidimensional array using php?


Antivirus
05-12-2008, 02:16 AM
I have always done all my sorting of data within the sql query, however for once, i need to do it in php and since ive never done this in php, i'm a bit stumped, hoping someione can assist...

My array looks like this:




Array
(
[0] => Array
(
[groupid] => 66
[name] => SOTE
[description] => Lorem ipsum dolor sit amet
[sc_ispd] => 1
[dateline] => 1204247554
)

[1] => Array
(
[groupid] => 88
[name] => LOS
[description] => Lorem ipsum dolor sit amet
[sc_ispd] => 0
[dateline] => 1204779261
)

[2] => Array
(
[groupid] => 1
[name] => MEGA
[description] => Lorem ipsum dolor sit amet
[sc_ispd] => 1
[dateline] => 1202601980
)

[3] => Array
(
[groupid] => 86
[name] => CRABS
[description] => Lorem ipsum dolor sit amet
[sc_ispd] => 1
[dateline] => 1204777825
)

)


What I need to do is re-sort it as if doing the sort in sql like so:
ORDER BY sc_ispd DESC, dateline DESC, groupid DESC

I'm pretty sure i need to use array_multisort() to do this, but having some difficulty with it. Is it even possible to do what i am trying to do here?

MoT3rror
05-12-2008, 04:56 AM
foreach($array AS $key => $value)
{
$arraykeys["$key"] = $value['sc_ispd'];
}

rsort($arraykeys);

foreach($arraykeys AS $key)
{
$data = $array["$key"];
}


This is how I did it but bet there is probably a better way that I wish I knew how to do. Also you can replace rsort with any array sort function. (http://www.php.net/sort)

Antivirus
05-12-2008, 07:21 PM
Thanks - that worked for sorting on one criteria, however since i need to sort on multiple criteria, I had to dig around a bit but finally found a function on php.net with works for me and i'll post it here for others:


/**
* Sorts a multidimensional array by more than one sort values (originally written by Raveler)
*
* @param array The multidimensional array we are trying to sort
* @param overload The sort criteria is overloaded as "sort1", ASC, "sort2" DESC, etc...
*
* @return array sorted array
*/
function sc_sortarray()
{
$arguments = func_get_args();
$array = $arguments[0];
$code = '';
for ($c = 1; $c < count($arguments); $c += 2)
{
if (in_array($arguments[$c + 1], array("ASC", "DESC")))
{
$code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
if ($arguments[$c + 1] == "ASC")
{
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
}
else
{
$code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
}
}
}
$code .= 'return 0;';
$compare = create_function('$a,$b', $code);
usort($array, $compare);
return $array;
}


Proper syntax would be like follows:
$array = sc_sortarray($array, "sc_ispaid", DESC, "dateline", DESC, "groupid", DESC);