I have an array as follows:
//0-based index, 2 dimensions
$data = array(
array(
'name'=>'EJA210E',
'id'=>439,
'region_id'=>17,
.. other attributes ..
),
array(
'name'=>'EJA210E',
'id'=>440,
'region_id'=>3,
),
array(
'name'=>'EJA210E',
'id'=>439,
'region_id'=>15,
),
.. etc..
);
What would be sort, first by name, then by id, then by region_id? Sorting by any one of these is no problem; I would simply loop through and get the name attribute, then re-order, however doing this three times I do not understand how to do.
You can try array_multisort by passing different ordering columns as shown below :
$data = array(
array(
'name'=>'EJA210E',
'id'=>439,
'region_id'=>17,
),
array(
'name'=>'EJA210E',
'id'=>440,
'region_id'=>3,
),
array(
'name'=>'AJA210E',
'id'=>438,
'region_id'=>15,
)
);
// Obtain a list of columns
foreach ($data as $key => $row) {
$name[$key] = $row['name'];
$id[$key] = $row['id'];
$region[$key] = $row['region_id'];
}
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($name, SORT_DESC, $id, SORT_DESC,$region, SORT_DESC, $data);
You could use usort() with a custom sorting function. Here's an example:
function cmp($a, $b)
{
if ($a['name'] == $b['name']) {
if ($a['id'] == $b['id']) {
if ($a['region_id'] == $b['region_id']) {
return 0;
}
return $a['region_id'] < $b['region_id'] ? -1 : 1;
}
return $a['id'] < $b['id'] ? -1 : 1;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
usort($data, 'cmp');
OK, I already got this question in stackoverflow but sadly it's in javascript - Javascript - sort array based on another array
and I want it in PHP
$data = array(
"item1"=>"1",
"item2"=>"3",
"item3"=>"5",
"item4"=>"2",
"item5"=>"4"
);
to match the arrangement of this array:
sortingArr = array("5","4","3","2","1");
and the output I'm looking for:
$data = array(
"item3"=>"5",
"item5"=>"4",
"item2"=>"3",
"item4"=>"2",
"item1"=>"1"
);
Any idea how this can be done?
Thanks.
For a detailed answer, why array_multisort does not match your needs, view this answer, please:
PHP array_multisort not sorting my multidimensional array as expected
In short: You want to sort an array based on a predefined order. The Answer is also given over there, but i copied one solution to this answer, too:
Use usort and array_flip, so you be able to turn your indexing array (ValueByPosition) into a PositionByValue Array.
$data = array(
"item1"=>"1",
"item2"=>"3",
"item3"=>"5",
"item4"=>"2",
"item5"=>"4"
);
usort($data, "sortByPredefinedOrder");
function sortByPredefinedOrder($leftItem, $rightItem){
$order = array("5","4","3","2","1");
$flipped = array_flip($order);
$leftPos = $flipped[$leftItem];
$rightPos = $flipped[$rightItem];
return $leftPos >= $rightPos;
}
print_r($data);
// usort: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
// uasort: Array ( [item3] => 5 [item5] => 4 [item2] => 3 [item4] => 2 [item1] => 1 )
However this would require you to predict all possible items inside the predefined order array, or thread other items in an appropriate way.
If you want to maintain the assoc keys, use uasort instead of usort.
Pretty simple ?
$data = array(
"item1"=>"1",
"item2"=>"3",
"item3"=>"5",
"item4"=>"2",
"item5"=>"4"
);
$sortingArr = array("5","4","3","2","1");
$result = array(); // result array
foreach($sortingArr as $val){ // loop
$result[array_search($val, $data)] = $val; // adding values
}
print_r($result); // print results
Output:
Array
(
[item3] => 5
[item5] => 4
[item2] => 3
[item4] => 2
[item1] => 1
)
using usort() the right way i think
Sort an array by values using a user-defined comparison function
you can do as follow:
$data = array(
"item1"=>"1",
"item2"=>"3",
"item3"=>"5",
"item4"=>"2",
"item5"=>"4"
);
$sortingArr = array("5","4","3","2","1");
$keys = array_flip($sortingArr);
usort($data, function ($a, $b) use ($keys) {
return $keys[$a] > $keys[$b] ? 1 : -1;
});
print_r($data);
// Output
// Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
live example: https://3v4l.org/75cnu
Look at my following snippet to sort your array based on another array:
$res_arr = array();
for ($i = 0; $i < count($sortingArr); $i++) {
for ($j = 0; $j < count($data); $j++) {
if($data[$j] == $sortingArr[$i]) {
$res_arr[] = $data[$j];
break;
}
}
}
// $res_array is your sorted array now
Look at code snippet to make a multidimensional array sort in order of input
$input_format_list = [4, 1];
$data = array(
"0" => array(
"School" => array(
"id" => 1,
"name" => "ST.ANN'S HIGH SCHOOL",
)
),
"1" => array(
"School" => array(
"id" => 4,
"name" => "JYOTI VIDHYA VIHAR",
)
)
);
$result = array(); // result array
foreach($input_format_list as $key => $value){ // loop
foreach ($data as $k => $val) {
if ($data[$k]['School']['id'] === $value) {
$result[$key] = $data[$k];
}
}
}
return $result;
Take a look at array_multisort. I'm not completely sure how to use it, as I have never found a practical use for it (I prefer to use usort to clearly define my terms), but it might work for you.
<?php
$data = array(
"item1"=>"1",
"item2"=>"3",
"item3"=>"5",
"item4"=>"2",
"item5"=>"4"
);
$result=array_flip($data);
krsort($result);
$result=array_flip($result);
print_r($result);
//use rsort for the index array
$sortingArr = array("5","4","3","2","1");
print_r($sortingArr);
I'm pretty proud of my solution:
uasort($data, function($a, $b) use ($sortingArr) {
return array_search($a, $sortingArr) <=> array_search($b, $sortingArr);
});
Working example: https://3v4l.org/bbIk2
It uses uasort to maintain the key-value associations as the OP requested. (unlike #hassan's otherwise elegant solution)
It doesn't require that every element in the $data array be present in the sorting array. (like #HamZa's solution)
It's brief.
It uses the spaceship operator <=> for comparison instead of more verbose logic.
Code:
Expanding on the Answer of Andrew, if you want the undefined entries in the sorting array to appear at the end of the output array:
uasort($currentTags, function ($a, $b) use ($sortingArr) {
if (in_array($a, $sortingArr) && !in_array($b, $sortingArr)) return -1;
if (!in_array($a, $sortingArr) && in_array($b, $sortingArr)) return 1;
if (!in_array($b, $sortingArr)) return -1;
return array_search($a, $sortingArr) <=> array_search($b, $sortingArr);
});
here is my array sample $data[][];
Array( [0] => Array ( [id] => 1349
[rating1] => 1.9378838029981E-7
[rating2] => 1.1801796607774 )
[1] => Array ( [id] => 1350
[rating1] => 5.5499981876923E-7
[rating2] => 1.5121329727308 )
[2] => Array ( [id] => 1377
[rating1] => 0.00023952225410117
[rating2] => 2.1947077830236 )
[3] => Array ( [id] => 1378
[rating1] => 0.00022982302863634
[rating2] => 2.2135588326622 )
[4] => Array ( [id] => 1379
[rating1] => 0.00026272979843585
[rating2] => 2.2388295595073 )
[5] => Array ( [id] => 1380
[rating1] => 0.0002788640872546
[rating2] => 2.1815325502993 )
)
I want to find max($data[][rating?]) but return $data[id][max_rating?] i.e. id associated with the max value.
Finding the max was easy for one particular, say rating1, I used array_reduce as follows (this is inspired from this SO ):
$max = array_reduce($data, function($a, $b) {
return $a > $b['rating1'] ? $a : $b['rating1'];
});
Now I have two questions :
1. How can I extend above array_reduce to include rating2 ? I have other ratingX as well.
2. I do not want the max value, rather the $data[][id] associated with the max.
I am not so much concerned about Q1, but the second one is important as I don't want to search through the array again to get associated $data[][id].
One line of thought is to use array_map instead of array_reduce, but I couldn't come up with a version which will pass on both [id] and [rating?]. Also, there are complications when I try to max() multiple rating? at one shot, as each rating will have different max, which in turn associates with different [id].
EDIT : Just to be clear, I want all the respective ids associated with respective max of each rating?
assuming your array is unsorted you have to loop through it at least once (either manually or using builtin functions). i'd use the following code:
$array = array(
array( 'id' => 1349, 'sudhi_rating1' => 1.9378838029981E-7, 'sudhi_rating2' => 1.1801796607774 ),
array( /* … */ ),
/* … */
);
$idx_max = 0;
foreach($array as $idx => $item) {
if($item['sudhi_rating1'] > $array[$idx_max]['sudhi_rating1'])
$idx_max = $idx;
}
echo "Rating 1 has max value at id ", htmlspecialchars($array[$idx_max]['id']);
you can extend the code to check multiple ratings at once (make $idx_max an array itself and add more ifs):
$idx_max = array (
'sudhi_rating1' => 0,
'sudhi_rating2' => 0,
/* … */ );
foreach($array as $idx => $item) {
foreach($idx_max as $rating => &$max) {
if($item[$rating] > $array[$max][$rating])
$max = $idx;
}
}
foreach($idx_max as $rating => $max)
echo 'Max value for ', htmlspecialchars($rating), ' has id ', htmlspeciachars($array[$max]['id']);
$max = array_reduce($data, function($a, $b) {
if (is_null($a)) return $b;
return max($a['rating1'],$a['rating2'])>max($b['rating1'],$b['rating2']) ? $a : $b;
});
Result: no Entries $max= NULL otherwise $max['id'] is the id with the max rating
Alternatively this generic code
$max = array_reduce($data, function($a, $b) {
if (is_null($a)) return $b;
return maxRating($a)>maxRating($b) ? $a : $b;
});
function maxRating($row){
return (max(array_intersect_key($row,array_flip(array_filter(array_keys($row),function ($item) { return strstr($item,'rating')!==FALSE;})))));
}
Will find for all ratings of the form rating?
EDIT -- The code was trying to answer Q1 here is the answer for just Q2
$max = array_reduce($data, function($a, $b) {
if (is_null($a)) return $b;
return $a['rating1']>$b['rating1'] ? $a : $b;
});
EDIT2 -- This is a generic solution for any number of rating? columns
$ratingKeys=array_filter(array_keys($data[0]),function ($item) { return strstr($item,'rating')!==FALSE;});
$max = array_reduce($data,function($a,$b) use (&$ratingKeys) {
if (is_null($a)) {
$a=array();
foreach($ratingKeys as $key) {
$a[$key]=$b[$key];
$a[$key.'_id'] = $b['id'];
}
return $a;
}
foreach($ratingKeys as $key) {
if ($a[$key]<$b[$key]) {
$a[$key]=$b[$key];
$a[$key.'_id']=$b['id'];
}
}
return $a;
});
This code results in
array(4) {
["rating1"]=> float(0.0002788640872546)
["rating1_id"]=> int(1380)
["rating2"]=> float(2.2388295595073)
["rating2_id"]=> int(1379)
}
EDIT 3 -- If you change the format of the input array to use id as the array key, you can massively simplify
$max=array_reduce(array_keys($data),function ($a,$b) use (&$data) {
if (is_null($a)) $a=array();
foreach(array_keys($data[$b]) as $item) {
if (!isset($a[$item]) {
$a[$item] = $b;
} else {
if ($data[$a[$item]][$item]) < $data[$b][$item]) $a[$item]=$b;
}
return $a;
}
});
This code results in
array(2) {
["rating1"]=> int(1380)
["rating2"]=> int(1379)
}
Given this array:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory's elements by price to get:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
You are right, the function you're looking for is array_multisort().
Here's an example taken straight from the manual and adapted to your case:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
As of PHP 5.5.0 you can use array_column() instead of that foreach:
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
PHP 7+
As of PHP 7, this can be done concisely using usort with an anonymous function that uses the spaceship operator to compare elements.
You can do an ascending sort like this:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usort takes a user-provided comparison function that must behave as follows (from the docs):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
And note also that <=>, the spaceship operator,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
which is exactly what usort needs. In fact, almost the entire justification given for adding <=> to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it
makes writing ordering callbacks for use with usort() easier
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort to sort our array, but it's a little more verbose and harder to understand:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort has to return integers for usort to work properly:
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
This is an important trap to bear in mind when using usort in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.
While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
If you want Case Insensitive Sort on strings, you can use SORT_NATURAL|SORT_FLAG_CASE
array_multisort(array_column($inventory, 'key_name'), SORT_DESC, SORT_NATURAL|SORT_FLAG_CASE, $inventory);
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
I ended on this:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array.
Like:
sort_array_of_array($inventory, 'price');
You can use usort with anonymous function, e.g.
usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
From Sort an array of associative arrays by value of given key in php:
by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order.
Example :
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
usort($array, "cmp");
print_r($array);
Output:
Array
(
[0] => Array
(
[price] => 200.0
[product] => test3
)
[1] => Array
(
[price] => 1000.50
[product] => test1
)
[2] => Array
(
[price] => 8800.50
[product] => test2
)
)
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."\n\n");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."\n");
}
outputs:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
For PHP 7 and later versions.
/**
* A method for sorting associative arrays by a key and a direction.
* Direction can be ASC or DESC.
*
* #param $array
* #param $key
* #param $direction
* #return mixed $array
*/
function sortAssociativeArrayByKey($array, $key, $direction){
switch ($direction){
case "ASC":
usort($array, function ($first, $second) use ($key) {
return $first[$key] <=> $second[$key];
});
break;
case "DESC":
usort($array, function ($first, $second) use ($key) {
return $second[$key] <=> $first[$key];
});
break;
default:
break;
}
return $array;
}
Usage:
$inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");
I use uasort like this
<?php
$users = [
[
'username' => 'joe',
'age' => 11
],
[
'username' => 'rakoto',
'age' => 21
],
[
'username' => 'rabe',
'age' => 17
],
[
'username' => 'fy',
'age' => 19
],
];
uasort($users, function ($item, $compare) {
return $item['username'] >= $compare['username'];
});
var_dump($users);
As of PHP 7.4, you can use arrow function:
usort(
$inventory,
fn(array $a, array $b): int => $b['price'] <=> $a['price']
);
Code (demo):
$inventory = [
['type' => 'fruit', 'price' => 3.50],
['type' => 'milk', 'price' => 2.90],
['type' => 'pork', 'price' => 5.43],
];
usort(
$inventory,
fn(array $a, array $b): int => $b['price'] <=> $a['price']
);
print_r($inventory);
(condensed) Output:
Array
(
[0] => Array ([type] => pork, [price] => 5.43)
[1] => Array ([type] => fruit, [price] => 3.5)
[2] => Array ([type] => milk, [price] => 2.9)
)
Was tested on 100 000 records:
Time in seconds(calculated by funciton microtime).
Only for unique values on sorting key positions.
Solution of function of #Josh Davis:
Spended time: 1.5768740177155
Mine solution:
Spended time: 0.094044923782349
Solution:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
try this:
$prices = array_column($inventory, 'price');
array_multisort($prices, SORT_DESC, $inventory);
print_r($inventory);
This function is re-usable:
function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
uasort($array, function($a, $b) use($key, $callback) {
return call_user_func($callback, $a[$key], $b[$key]);
});
}
It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.
Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.
/**
* A method for sorting arrays by a certain key:value.
* SortByKey is the key you wish to sort by
* Direction can be ASC or DESC.
*
* #param $array
* #param $sortByKey
* #param $sortDirection
* #return array
*/
private function sortArray($array, $sortByKey, $sortDirection) {
$sortArray = array();
$tempArray = array();
foreach ( $array as $key => $value ) {
$tempArray[] = strtolower( $value[ $sortByKey ] );
}
if($sortDirection=='ASC'){ asort($tempArray ); }
else{ arsort($tempArray ); }
foreach ( $tempArray as $key => $temp ){
$sortArray[] = $array[ $key ];
}
return $sortArray;
}
to change the method to sort objects simply change the following line:
$tempArray[] = strtolower( $value[ $sortByKey ] );
to
$tempArray[] = strtolower( $value->$sortByKey );
To run the method simply do
sortArray($inventory,'price','ASC');
You might try to define your own comparison function and then use usort.
//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
#uasort($inventory, "cmp");
print_r($inventory);
//result
Array
(
[2] => Array
(
[type] => pork
[price] => 5.43
)
[0] => Array
(
[type] => fruit
[price] => 3.5
)
[1] => Array
(
[type] => milk
[price] => 2.9
)
)
Many people are searching for a way to do this with Laravel and ending up here. Also, some Laravel questions are getting closed due to duplicates to this question.
Hence, I shared an easy way to perform it with Laravel collect() method.
$inventory = collect($inventory)->sortBy('price')->toArray();
For Descending order
$inventory = collect($inventory)->sortBy('price')->reverse()->toArray();
Or,
$inventory = collect($inventory)->('price')->reverse()->toArray();
Complete Dynamic Function
I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.
Simple function to sort an array by a specific key. Maintains index association
<?php
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
$people = array(
12345 => array(
'id' => 12345,
'first_name' => 'Joe',
'surname' => 'Bloggs',
'age' => 23,
'sex' => 'm'
),
12346 => array(
'id' => 12346,
'first_name' => 'Adam',
'surname' => 'Smith',
'age' => 18,
'sex' => 'm'
),
12347 => array(
'id' => 12347,
'first_name' => 'Amy',
'surname' => 'Jones',
'age' => 21,
'sex' => 'f'
)
);
print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
If you need to sort an array of strings with different cases, this will change the sorting array values to lowercase.
$data = [
[
'name' => 'jack',
'eyeColor' => 'green'
],
[
'name' => 'Amy',
'eyeColor' => 'brown'
],
[
'name' => 'Cody',
'eyeColor' => 'blue'
]
];
function toLowerCase($a) { return strtolower($a); }
$sortArray = array_map("toLowerCase",array_column($data, 'name'));
array_multisort($sortArray, SORT_ASC, $data);
This function works 100% on all major versions of PHP and it is tested with PHP5, PHP7, PHP8.
function sort_my_array($array, $order_by, $order)
{
switch ($order) {
case "asc":
usort($array, function ($first, $second) use ($order_by) {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
return $first[$order_by] <=> $second[$order_by];
} else {
$array_cmp = strcmp($first[$order_by], $second[$order_by]);
return $array_cmp ;
}
});
break;
case "desc":
usort($certificates, function ($first, $second) use ($order_by) {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
return $first[$order_by] <=> $second[$order_by];
} else {
$array_cmp = strcmp($first[$order_by], $second[$order_by]);
return -$array_cmp ;
}
});
break;
default:
break;
}
return $array;
}
$arr1 = array(
array('id'=>1,'name'=>'aA','cat'=>'cc'),
array('id'=>2,'name'=>'aa','cat'=>'dd'),
array('id'=>3,'name'=>'bb','cat'=>'cc'),
array('id'=>4,'name'=>'bb','cat'=>'dd')
);
$result1 = array_msort($arr1, array('name'=>SORT_DESC);
$result2 = array_msort($arr1, array('cat'=>SORT_ASC);
$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
function array_msort($array, $cols)
{
$colarr = array();
foreach ($cols as $col => $order) {
$colarr[$col] = array();
foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}
$eval = 'array_multisort(';
foreach ($cols as $col => $order) {
$eval .= '$colarr[\''.$col.'\'],'.$order.',';
}
$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
foreach ($arr as $k => $v) {
$k = substr($k,1);
if (!isset($ret[$k])) $ret[$k] = $array[$k];
$ret[$k][$col] = $array[$k][$col];
}
}
return $ret;
}
try this:
asort($array_to_sort, SORT_NUMERIC);
for reference see this:
http://php.net/manual/en/function.asort.php
see various sort flags here:
http://www.php.net/manual/en/function.sort.php