Home PHP JavaScript CSS WordPress APIs .htaccess Other How-To Useful Scripts What I Recommend
Posted on by Aleksandar Gichevski ()

Multidimensional arrays are nice way to combine your data. PHP have great support for arrays including sorting functions for one-column and multi-column.

Sorting single-column array is very easy by using sort() function and for sorting multi-column array is used function array_multisort().

Let’s look at the function for sorting multidimensional arrays.

Here is Multidimensional Array Data Example:

  $data[0]['name']= 'John';
  $data[0]['last_name'] = 'Brownes';
  $data[0]['age'] = 34;
  $data[0]['height'] = 184;

  $data[1]['name']= 'Peter';
  $data[1]['last_name'] = 'Jackson';
  $data[1]['age'] = 27;
  $data[1]['height'] = 178;

  $data[2]['name']= 'Joseph';
  $data[2]['last_name'] = 'Cartner';
  $data[2]['age'] = 56;
  $data[2]['height'] = 172;

Assume you want to sort this array by 'age' you will need to place 'age' column as a separate, single-column array. This can be done with foreach command:

foreach ($data as $val)
 $tmp[] = $val['age'];

Now the newly created $tmp array you place into function array_multisort as parameter 1, as parameter 2 you enter the way of sorting SORT_ASC or SORT_DESC and as parameter 3 you place the multidimensional array.

This is how it should look for descending sort:

array_multisort($tmp, SORT_DESC, $data);

If you want to sort the array by more than one column let’s say 'age' and 'name' do the same as we did before… so create another one-column array for 'name' value and add it into the function.

foreach ($data as $val)
 $tmp_age[] = $val['age'];

foreach ($data as $val)
 $tmp_name[] = $val['name'];

array_multisort($tmp_age, SORT_DESC, $tmp_name, $data);

Other Posts You Might Like

Get a fast, free website audit

Enter your URL below to get full in-depth SEO report and tips.

Useful Scripts

Most Popular Posts

Recent Posts

June 14th, 2014
Website Optimization Using Gzip Compression

June 10th, 2014
Google Search AutoComplete API

May 14th, 2014
What is a Tag Cloud and How to Calculate it by Formula

March 27th, 2014
Error writing file /tmp (errcode 28) Solved!

February 15th, 2014
Fixed CSS & HTML Navigation Bar

February 9th, 2014
Benchmark Your Server (CPU, File IO, MySQL) with SysBench

February 8th, 2014
JavaScript Array Basics

January 29th, 2014

January 25th, 2014
Payoneer Debit Card for Freelancers to receive money online

January 24th, 2014
How HTML Color Codes are generated?

Read Latest Posts directly on Facebook