How to Sort a Multi-dimensional Array by Value
Try a usort. If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Starting in PHP 5.3, you can use an anonymous function:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
With PHP 7 you can use the spaceship operator:
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Finally, in PHP 7.4 you can clean up a bit with an arrow function:
usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
If you need to retain key associations, use uasort()
- see comparison of array sorting functions in the manual.
Sort multidimensional array in PHP using foreach
array_multisort
sorts the array in place, it does not return the sorted array. You need to use it like this:
foreach ($slice1 as $col) {
array_multisort($col);
$slicesort[] = $col;
}
Having said this, array_multisort
is somewhat overkill here, and I'm not sure that you really need to create a copy of the array. This will do just fine:
foreach ($slice1 as &$col) {
sort($col);
}
This applies sort
to each array within $slice1
by reference, and thereby orders $slice1
in place.
PHP - Sort multi-dimensional array by another array
There is no built-in function for this in PHP and i am unable to think of any custom function, which would do this using usort. But array_map is simple enough, imo, so why not use it instead?
$sorted = array_map(function($v) use ($data) {
return $data[$v - 1];
}, $order);
PHP - How to sort multidimensional array by Key?
Working demo.
You can use array_multisort to achieve your requirement.
$keys = [];
foreach($arr as $k => $item){
$keys[] = key($item);
}
array_multisort($keys, SORT_NATURAL, $arr);
array_multisort — Sort multiple or multi-dimensional arrays
SORT_NATURAL - compare items as strings using "natural ordering" like natsort().
How to sort a multidimensional array by First Name in php?
You can use usort function which sorts arrays using a user-defined comparison function:
usort($array, function($v1, $v2) { return strcmp($v1['firstName'], $v2['firstName']); });
Or you can use sorted function from Nspl:
use function \nspl\a\sorted;
$sorted = sorted($array, 'firstName');
How do I sort a multidimensional array with stdClass Objects by values of a key?
You're almost right, but $row[$col]
tries to access the objects like an array. You want something like $row->{$col}
instead. Here's a simpler, working example:
$db = array(
0 => (object) array('name' => 'Business3'),
1 => (object) array('name' => 'Business2'),
2 => (object) array('name' => 'Business1')
);
$col = 'name';
$sort = array();
foreach ($db as $i => $obj) {
$sort[$i] = $obj->{$col};
}
$sorted_db = array_multisort($sort, SORT_ASC, $db);
print_r($db);
Outputs:
Array
(
[0] => stdClass Object
(
[name] => Business1
)
[1] => stdClass Object
(
[name] => Business2
)
[2] => stdClass Object
(
[name] => Business3
)
)
How do I sort a multidimensional array by one of the fields of the inner array in PHP?
You need to use usort, a function that sorts arrays via a user defined function. Something like:
function cmp($a, $b)
{
if ($a["price"] == $b["price"]) {
return 0;
}
return ($a["price"] < $b["price"]) ? -1 : 1;
}
usort($yourArray,"cmp")
Sort PHP multi-dimensional array based on value in inner array?
Thinking,more useful and practical
http://php.net/manual/en/function.sort.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;
}
How to use
$list = array(
array( 'type' => 'suite', 'name'=>'A-Name'),
array( 'type' => 'suite', 'name'=>'C-Name'),
array( 'type' => 'suite', 'name'=>'B-Name')
);
$list = array_sort($list, 'name', SORT_ASC);
array(3) { [0]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "A-Name" } [2]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "B-Name" } [1]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "C-Name" } }
How do I Sort a Multidimensional Array in PHP
You can use array_multisort()
Try something like this:
foreach ($mdarray as $key => $row) {
// replace 0 with the field's index/key
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $mdarray);
For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:
array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);
Related Topics
How to Write a File in Utf-8 Format
Connect PHP to Mssql Via Pdo Odbc
Who Should Handle the Conditions in Complex Queries, the Data Mapper or the Service Layer
PHP Library For Parsing Xml With a Colons in Tag Names
Amazon S3 - How to Fix 'The Request Signature We Calculated Does Not Match the Signature' Error
How to Debug Pdo Database Queries
Count How Many Files in Directory PHP
What Is the Meaning of Three Dots (...) in PHP
Trying to Get Property of Non-object In
How to Login in With Curl and Ssl and Cookies
What Does "1" Mean At the End of a PHP Print_R Statement
Redefine Built in PHP Functions
Reference - Composer Error "Your PHP Version Does Not Satisfy Requirements" After Upgrading PHP
How to Combine Two Arrays Together