How To Sort A Multidimensional Array By One Element In PHP

H

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:

About the author

Alvin Poh

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.

Add comment

By Alvin Poh

About Author

I've over 17 years of entrepreneurship experience, having built a tech company to be the top in the country, which was subsequently acquired for an 8-figure sum. As CEO, I led the company through robust growth to 150 employees across 4 countries. After the acquisition, I embraced minimalism, sold off my personal possessions, and started living around the world.

Read more about my story here.