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
.
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);
How to sort Object Array Collection by value in PHP
You can either use usort()
$test = array(array("col_header" => "other_1",
"col_order" => 12,
"data" => "asdgasdgfasdg"),
array("col_header" => "other_2",
"col_order" => 10,
"data" => "dfhgsdhgsd"),
array("col_header" => "other_3",
"col_order" => 11,
"data" => "s"));
usort($test, function($a, $b)
{
if ($a["col_order"] == $b["col_order"])
return (0);
return (($a["col_order"] < $b["col_order"]) ? -1 : 1);
});
var_dump($test);
Output :
array (size=3)
0 =>
array (size=3)
'col_header' => string 'other_2' (length=7)
'col_order' => int 10
'data' => string 'dfhgsdhgsd' (length=10)
1 =>
array (size=3)
'col_header' => string 'other_3' (length=7)
'col_order' => int 11
'data' => string 's' (length=1)
2 =>
array (size=3)
'col_header' => string 'other_1' (length=7)
'col_order' => int 12
'data' => string 'asdgasdgfasdg' (length=13)
But I suggest you to sort your results directly from the SQL query :
SELECT *
FROM yourTable
...
ORDER BY col_order ASC
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');
How to sort an array of objects by a property of each object
The second paramater to usort
should be a function. See http://php.net/manual/en/function.usort.php. You would need to pass it a function like:
function cmp($a, $b)
{
return strcmp($a->title, $b->title);
}
I think you would then call it like usort($restrictedEvents, "cmp");
.
How to sort PHP object array by a nested object property several levels deep?
<?php
//sample data
$arr = array(
array(
'id' => 1,
'Start' => 210.4
),
array(
'id' => 2,
'Start' => 105.1
)
);
//define the comparator (assuming that 'Start' is a numeric property)
function cmp($a, $b){
if($a['Start'] < $b['Start']){
return -1;
}else if($a['Start'] > $b['Start']){
return 1;
}
return 0;
}
//sort the array
usort($arr, "cmp");
print_r($arr);
?>
Related Topics
Tell Selinux to Give Apache Execute Access to PHP Files Outside Document Root
Check for Session Timeout in Laravel
Get_Instance() in Codeigniter: Why Assign It to a Variable
Supplied Argument Is Not a Valid MySQL Result Resource
Place PHP Results Inside HTML Page
Jquery Tablesorter Index Column Insert
Display Single Column Value of MySQLi Query
Send Post Data via Raw JSON with Postman
PHP String in Array Only Returns First Character
How to Rename Column in Laravel Using Migration
Parse Timezone Int to String (Timezone Name) (Facebook API)
Laravel: Auth::User()->Id Trying to Get a Property of a Non-Object
Converting Named HTML Entities to Numeric HTML Entities
How to Minify Js in PHP Easily...Or Something Else
PHP Warning:Mysqli_Num_Rows() Expects Parameter 1 to Be MySQLi_Result, Object Given