Sort Object in PHP

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.

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

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 can I sort object on laravel?

Don't reinvent the wheel. Laravel is a fantastic framework that did lots of work for you already.

First, you need to convert your array to a Collection:

$c = collect($c);

Now, For working with collections, you have a nice set of available methods you can work with. In your case, you need the sortBy():

$sorted = $c->sortBy('id');

Alternatively, you can pass a callback:

$sorted = $c->sortBy(function ($item, $key) {
return $item->id;
});

Both of these will return a Collection object. If you want to get an Array back instead, use all() or toArray() on your result:

$c = $c->all();

// or

$c = $c->toArray();

Sort Object in PHP

Almost verbatim from the manual:

function compare_weights($a, $b) { 
if($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}

usort($unsortedObjectArray, 'compare_weights');

If you want objects to be able to sort themselves, see example 3 here: http://php.net/usort

sort object by integer key in PHP

Have you tried ksort?

ksort

(PHP 4, PHP 5, PHP 7) ksort — Sort an array by key

Description

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Sorts
an array by key, maintaining key to data correlations. This is useful
mainly for associative arrays.

If it doesn't deal well with numeric-strings keys you can use uksort and write your compare function with a parseInt and spaceship operator (<=>).


If you, however, want to simply stop the reordering fully, altought you can't stop the "sorting" of the object by its keys (and note that it is not standard and is browser-dependent: not all of them will sort it), you can always use pairs inside an array to avoid changes to your original order of elements (pairs, in this case):

$a = [
['33', 'first'],
['25', 'second'],
['14', 'last']
];



Related Topics



Leave a reply



Submit