PHP">Sorting a multidimensional array in PHP

After search­ing the inter­net for some­thing trivial like the sort­ing a mul­ti­di­men­sional array I found the fol­low­ing solution.


function sort_multi_array(&$array, $key)
{
foreach($array as &$value) {
$value['__________'] = $value[$key];
}
/* Note, if your functions are inside of a class, use:
usort($array, array("My_Class", 'sort_by_dummy_key'));
*/

usort($array, 'sort_by_dummy_key');

foreach($array as &$value) {   // removes the dummy key from your array
unset($value['__________']);
}
return $array;
}

function sort_by_dummy_key($a, $b)
{
if($a['__________'] == $b['__________']) return 0;
if($a['__________'] < $b['__________']) return -1;
return 1;
}

 

Looks a little bit weird but it gives the simple abil­ity to just pass in the array and the key you want your array sor­ted by.

So for an array like this:


$dimension_array = array( array("source"=>"google.com/images", "dimensions"=>156000), array("source"=>"bing.com/images", "dimensions"=>12000), array("source"=>"flickr.com/images", "dimensions"=>160000));

You would make one simple call and if you want the res­ult in reverse order you simple reverse the array and you’re done.


$sorted = sort_multi_array($dimension_array, "dimensions");

// If you want your sorted array in reverse order
$final_image_array = array_reverse( $sorted );

 

As I men­tioned the “sort_multi_array” looks a little weird but it is quite simple. What it does is, it takes your passed $key para­meter and assigns it to a value with a dummy key. Now we can just use the easy “usort” func­tion to com­pare the “keys” and finally we remove the “dummy_key. Done.

I found this code here.

If you have ques­tions leave me a comment.

Categories: PHP Tags: , ,
  1. May 1st, 2011 at 18:40 | #1

    Thank you..really informative!!

  2. April 10th, 2013 at 16:00 | #2

    Hmm is any­one else exper­i­en­cing prob­lems with the images on this blog load­ing? I’m try­ing to find out if its a prob­lem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

    • April 10th, 2013 at 16:14 | #3

      Hi, do you have a flash plu­gin installed?
      It’s work­ing fine for me using Mac OS X from New Zealand.

  1. No trackbacks yet.