PHP array multiple sort - by value then by key?
Have a look at examples #3:
http://php.net/manual/en/function.array-multisort.php
You'll need to create two arrays to use as indexes; one made up of the original array's keys and the other of the original array's values.
Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).
How to sort an array of associative arrays by value of a given key in PHP?
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);
sort array by multiple keys with optional key
You can use usort
to accomplish this with isset
checks for versesFirst
key.
Snippet:
<?php
usort($data, function($a,$b){
$book_id_1 = intval($a['bookID']);
$book_id_2 = intval($b['bookID']);
if($book_id_1 != $book_id_2) return $book_id_1 <=> $book_id_2;
$chapter_1 = intval($a['chapter']);
$chapter_2 = intval($b['chapter']);
if($chapter_1 != $chapter_2) return $chapter_1 <=> $chapter_2;
if(!isset($b['versesFirst'])){
return -1;
}
if(!isset($a['versesFirst'])){
return 1;
}
return intval($a['versesFirst']) <=> intval($b['versesFirst']);
});
print_r($data);
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 an array by multiple keys in PHP
Use usort().
Example:
$byPlayerID = function($player, $compare) {
if($player['player_id'] > $compare['player_id'])
return 1; // move up
else if($player['player_id'] < $compare['player_id'])
return -1; // move down
else
return 0; // do nothing
};
usort($players, $byPlayerID);
// now $players is sorted!
This does require PHP 5.3 though, below is a more backwards compatible version
function byPlayerID($player, $compare) {
if($player['player_id'] > $compare['player_id'])
return 1; // move up
else if($player['player_id'] < $compare['player_id'])
return -1; // move down
else
return 0; // do nothing
}
usort($players, "byPlayerID");
PHP sort array by two field values
array_multisort()
is the correct function, you must have messed up somehow:
// Obtain a list of columns
foreach ($data as $key => $row) {
$return_fare[$key] = $row['return_fare'];
$one_way_fare[$key] = $row['one_way_fare'];
}
// Sort the data with volume descending, edition ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);
If you take a look at the comments at PHP's manual page for array_multisort()
, you can find a very helpful array_orderby()
function which allows you to shorten the above to just this:
$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
To avoid the looping use array_column()
(as of PHP 5.5.0):
array_multisort(array_column($data, 'return_fare'), SORT_ASC,
array_column($data, 'one_way_fare'), SORT_ASC,
$data);
Related Topics
How to Implement a Web Scraper in PHP
Display Numbers With Ordinal Suffix in PHP
How to Remove the Querystring and Get Only the Url
Continue PHP Execution After Sending Http Response
Mixing a PHP Variable With a String Literal
How to Include Code into a PHP Class
Remove Script Tag from HTML Content
Fastest Way to Serve a File Using PHP
How Are Echo and Print Different in PHP
How to Show Multiple Recaptchas on a Single Page
Trying to Get Property of Non-Object - Laravel 5
Architecture More Suitable For Web Apps Than MVC
Remove Portion of a String After a Certain Character
PHP Sort Array by Two Field Values
Fpdf Error: Some Data Has Already Been Output, Can't Send Pdf