PHP Sort array by field?
Use usort
which is built explicitly for this purpose.
function cmp($a, $b)
{
return strcmp($a["title"], $b["title"]);
}
usort($array, "cmp");
Sort array of objects by one property
Use usort, here's an example adapted from the manual:
function cmp($a, $b) {
return strcmp($a->name, $b->name);
}
usort($your_data, "cmp");
You can also use any callable as the second argument. Here are some examples:
Using anonymous functions (from PHP 5.3)
usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);});
From inside a class
usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class
Using arrow functions (from PHP 7.4)
usort($your_data, fn($a, $b) => strcmp($a->name, $b->name));
Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count
as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count
.
sorting a column in a PHP array
You can use uasort
uasort($entity_list, 'mySort');
function mySort($a, $b) {
return ($a['student_last_name'] <==> $b['student_last_name']);
}
But if your data come from a DB, it would be a lot easier and lighter to ORDER BY.
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")
PHP sort array of objects by two properties
Why the extra level of indirection and making things more confusing? Why not usort directly with usort($objectArray, "sortObjects");
using a sortObjects($a,$b)
function that does what any comparator does: return negative/0/positive numbers based on the input?
If the tabs differ, return their comparison, if they're the same, return the order comparison; done.
$array = array(
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 12
),
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 8
),
(object)array(
'tab_option_name_selector' => 1,
'order' => 2,
'fieldtype' => 'selectbox'
),
(object)array(
'tab_option_name_selector' => 2,
'order' => 3,
'fieldtype' => 'selectbox'
)
);
function compareTabAndOrder($a, $b) {
// compare the tab option value
$diff = $a->tab_option_name_selector - $b->tab_option_name_selector;
// and return it. Unless it's zero, then compare order, instead.
return ($diff !== 0) ? $diff : $a->order - $b->order;
}
usort($array, "compareTabAndOrder");
print_r($array);
Sorting php array by column in ascending order
You can try this -
$new = array();
// Extract and get the keys as values
$order = array_flip($array['order']);
// sort them according to keys
ksort($order);
// loop through main array
foreach($array as $key => $sub_array) {
// loop through order
foreach ($order as $o) {
// store the new value according to order
$new[$key][] = $sub_array[$o];
}
}
Demo
Sort array of objects by property value inside a function
as always, sorting algorithm uses a compare function behind the scene to sort the whole array by comparing two element, for sorting complex stuff like this, one should write compare function and define the logic there for ordering
function compare($a, $b)
{
return strtotime($a->metadata['endtime']) < strtotime($b->metadata['endtime']);
}
usort($yourarray, 'compare');
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);
How to sort an array of objects by object field in PHP?
You'll need to write your own function to do the comparison. Once you have that function, you can then use usort - http://php.net/manual/en/function.usort.php
Note that this also works with sorting an array of objects, you just have to change your comparison function.
Related Topics
How to Iterate Over Non-English File Names in PHP
PHP Fatal Error: Call to Undefined Function MySQLi_Stmt_Get_Result()
Set Session Variable Using JavaScript in PHP
Custom Order Status Background Button Color in Woocommerce 3.3 Admin Order List
How to Access a Deep Object Property Named as a Variable (Dot Notation) in PHP
Is There a Good PHP Geolocation Service
PHP Simplexml Namespace Problem
How to Get Insert Id in Mssql in PHP
Get Numbers from String with PHP
Differencebetween the PHP Open Tags "<=" and "<Php"/"<"
Http Options Request on Azure Websites Fails Due to Cors
Strange Behaviour with Numbers That Have a Leading Zero
Sort Multi-Dimensional Array by Specific Key
How to Redirect After Download in Laravel
How to Check If an Uploaded File Is an Image Without Mime Type