...

View Full Version : Sorting multidimentional arrays with PHP



deafdigit
08-16-2012, 05:02 PM
Hi,


I have a multidimentional array (2 dimensions) and I'd like to sort the outer-most array according to a key of the inner-most arrays.



array(5) {
[0]=>
array(3) {
["id"]=>
int(1)
["navn"]=>
string(14) "Navn1"
["num"]=>
int(0)
}
[1]=>
array(3) {
["id"]=>
int(2)
["navn"]=>
string(17) "Navn2"
["num"]=>
int(0)
}
[2]=>
array(3) {
["id"]=>
int(3)
["navn"]=>
string(15) "Navn3"
["num"]=>
int(1)
}
[3]=>
array(3) {
["id"]=>
int(4)
["navn"]=>
string(23) "Navn4"
["num"]=>
int(0)
}
[4]=>
array(3) {
["id"]=>
int(5)
["navn"]=>
string(9) "Navn5"
["num"]=>
int(3)
}
}


I'd like to sort the outer array descending in regards to the "num"-key (so that "Mads Jensen" becomes the first item.

I found this function online:


function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}

Problem is it doesn't seem to do anything - nothing changes in the array.

Can anybody tell me why, or preferably "fix my function"?


Thanks in advance,
Deaf_digit

Fou-Lu
08-16-2012, 06:00 PM
That function is a little on the incomplete side. I wouldn't waste time correcting it though; comparators are far easier to use:


$a = array(
array('id' => 1, 'navn' => "Johnnie Adelby", 'num' => 0),
array('id' => 2, 'navn' => "Martin Carstensen", 'num' => 0),
array('id' => 3, 'navn' => "Julia S°rensen", 'num' => 1),
array('id' => 4, 'navn' => "RenÚ Rosenberg Nielsen", 'num' => 0),
array('id' => 5, 'navn' => "Mads Jensen", 'num' => 3)
);

function cmpNamesASC(array $a, array $b)
{
$iResult = 0;
if (isset($a['num'], $b['num']))
{
$iResult = $a['num'] - $b['num'];
if ($iResult == 0 && isset($a['navn'], $b['navn']))
{
$iResult = strcmp($a['navn'], $b['navn']);
}
}
return $iResult;
}

function cmpNamesDESC(array $a, array $b)
{
return cmpNamesASC($b, $a);
}

printf("Before: %s" . PHP_EOL, print_r($a, true));
usort($a, 'cmpNamesDESC');
printf("After: %s" . PHP_EOL, print_r($a, true));

deafdigit
08-17-2012, 08:23 AM
That looks very promising. I'll give that a go.

Thanks Fou-Lu.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum