How To Sort A Multidimensional Array By One Element In PHP

I had a table’s worth of listings and had stored all the values in a multidimensional array in PHP. The problem was, I needed to sort the multidimensional array, but based on just one element. Here’s the easiest, fastest solution that I found from the array_multisort function page of PHP (thanks to zequez at gmail dot com!).

Here’s his original solution taken from that page:

$multiArray = Array(
    Array("id" => 1, "name" => "Defg"),
    Array("id" => 2, "name" => "Abcd"),
    Array("id" => 3, "name" => "Bcde"),
    Array("id" => 4, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["name"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["name"]."
"; /* Outputs Abcd Bcde Cdef Defg */

My requirements are similar, but not exactly the same, and so I had to tweak the code slightly to fit my needs. I had a huge table of values, but needed to sort the entire multidimensional array by the second column, which was a column of price values. Here’s a simplified version of my tweaked code:

$itemtable = Array(
    Array(1, 253.12),
    Array(2, 569.24),
    Array(3, 85.69),
    Array(4, 91.27));
$tmp = Array();
  foreach($itemtable as &$ma) {
	$tmp[] = &$ma[1]; //this just refers to the 2nd element of my 2-element array
  array_multisort($tmp, $itemtable); 

And that’s it! That’s the fastest, easiest way that I found to sort a multidimensional array, but based on just one element.

Similar Posts:

Leave a reply:

Your email address will not be published.


Site Footer

Sliding Sidebar


The contents on this blog are not intended as professional advice. The author disclaims any liability, loss, or risk taken by individuals who directly or indirectly act on the information contained on this blog.