Jump to content

Sorting an array of associative arrays


bloodykis

Recommended Posts

I have a nested associative array, and i need to sort the children of the last parent by the values of one key.

 

Array ( [0] => Array ( [name] => website.jpg [mod] => 1216300822 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ ) [1] => Array ( [name] => island_wars.scm [mod] => 1216300823 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ ) [2] => Array ( [name] => preview.jpg [mod] => 1216300828 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ ) )

 

I need all of these to be in descending order by the [mod] key:

 

Array ( [2] => Array ( [name] => preview.jpg [mod] => 1216300828 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ ) [1] => Array ( [name] => island_wars.scm [mod] => 1216300823 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ ) [0] => Array ( [name] => website.jpg [mod] => 1216300822 [type] => hltv [game] => halo [dir] => demos/halo2/HLTV/ )  )

 

That is the order it should be in, but I have tried php's built-in sort functions, and tried doing them recursively with no luck.  The method has to be close to the speed of a qsort, bubble wont cut it.

 

Any help is greatly appreciated, this has been bugging me for a while now.

Link to comment
https://forums.phpfreaks.com/topic/116089-sorting-an-array-of-associative-arrays/
Share on other sites

Created right from the example in the manual for array_multisort(): http://us2.php.net/manual/en/function.array-multisort.php

 

Assuming $data_array is your array:

<?php

// Create an array of just the mod values
foreach ($data_array as $key => $row) {
   $mod[$key]  = $row['mod'];
}

// Sort the data with mod ascending. Add $data_array
// as the last parameter, to sort by the common key
array_multisort($mod, SORT_ASC, $data_array);

?>

 

Or you could also use usort(): http://us2.php.net/manual/en/function.usort.php

 

<?php

function sort_by_mod($a, $b)
{
   if ($a['mod'] == $b['mod']) { return 0; }
   return ($a['mod'] < $b['mod']) ? -1 : 1;
}

usort($data_array, 'sort_by_mod');

?>

Created right from the example in the manual for array_multisort(): http://us2.php.net/manual/en/function.array-multisort.php

 

Assuming $data_array is your array:

<?php

// Create an array of just the mod values
foreach ($data_array as $key => $row) {
   $mod[$key]  = $row['mod'];
}

// Sort the data with mod ascending. Add $data_array
// as the last parameter, to sort by the common key
array_multisort($mod, SORT_ASC, $data_array);

?>

 

 

added 2 lines of that to my existing loops and it works like a charm.  creative use w/ usort

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.