Array_multisort with natural sort

Is it possible to sort multiple dimensional arrays by multiple columns using the natural look in PHP? Here is an example. Suppose I have a 2D data array, for example,

$array[1]['Name'] = 'John';
$array[1]['Age'] = '20';
$array[1]['Code'] = 'ABC 12';

$array[2]['Name'] = 'John';
$array[2]['Age'] = '21';
$array[2]['Code'] = 'ABC 1';

$array[3]['Name'] = 'Mary';
$array[3]['Age'] = '20';
$array[3]['Code'] = 'ABC 10';

I want to sort this array by name (ASC), then by age (DESC) and by code (ASC), everything will be sorted naturally. Basically it will be array_multisort with natural sorting.

I have found many solutions on this topic on the Internet. Unfortunately, they only support sorting by one column, and not by several columns.

+5
source share
3 answers

, :

function myCmp($a, $b) {
 $nameCmp = strnatcasecmp($a['Name'], $b['Name']);
 $ageCmp = strnatcasecmp($a['Age'], $b['Age']);
 $codeCmp = strnatcasecmp($a['Code'], $b['Code']);

 if ($nameCmp != 0) // Names are not equal
   return($nameCmp);

 // Names are equal, let compare age

 if ($ageCmp != 0) // Age is not equal
   return($ageCmp * -1); // Invert it since you want DESC

 // Ages are equal, we don't need to compare code, just return the comparison result
   return($codeCmp);
}

usort($array, 'myCmp');

+6

PHP 5.4 , array_multisort SORT_NATURAL.

+1

This code will do the trick:

// Your original data stored in $array
$array[1]['Name'] = 'John';
$array[1]['Age'] = '20';
$array[1]['Code'] = 'ABC 12';

$array[2]['Name'] = 'John';
$array[2]['Age'] = '21';
$array[2]['Code'] = 'ABC 1';

$array[3]['Name'] = 'Mary';
$array[3]['Age'] = '20';
$array[3]['Code'] = 'ABC 10';

// Since array_multisort() needs arrays of columns we need to 
// transform it and preserve he keys
foreach ($array as $key => $row) {
    $names[$key] = $row['Name'];
    $ages[$key] = $row['Age'];
    $codes[$key] = $row['Code'];
}

// Sort it according to your criterias
array_multisort($names, SORT_ASC, $ages, SORT_DESC, $codes, SORT_ASC, $array);

// $array now contains your sorted array.

Link to the code: http://codepad.org/tr83Wt5J

0
source

All Articles