My object array ($c) like this :
Array
(
[0] => stdClass Object
(
[id] => 3
[name] => chelsea.png
)
[1] => stdClass Object
(
[id] => 4
[name] => arsenal.png
)
[2] => stdClass Object
(
[id] => 5
[name] => mu.png
)
[3] => stdClass Object
(
[id] => 1
[name] => city.png
)
)
I want to sort it by id
If in php normal I try like this :
function sort_by_id( $a, $b )
{
if( $a->id == $b->id ){ return 0 ; }
return ($a->id < $b->id) ? -1 : 1;
}
usort($c,'sort_by_id');
echo '<pre>';print_r($c);echo '</pre>';
It works
But How can I implement it use laravel?
I try like this :
public function add($param)
{
...
usort($c, $this->sortById());
echo '<pre>';print_r($c);echo '</pre>';die();
...
}
private function sortById($a, $b)
{
if($a->id == $b->id) {
return 0 ;
}
return ($a->id < $b->id) ? -1 : 1;
}
It does not work
There exist error like this :
Undefined property ... $sortById ...
How can I solve it?
To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database.
The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.
public function sortByScore ($a, $b) { return strcmp($a->score, $b->score); } $mySortedData = usort($myData, array($this, 'sortByScore'));
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();
Try this
public function add($param)
{
...
usort($c, function($a, $b){
if($a->id == $b->id) {
return 0 ;
}
return ($a->id < $b->id) ? -1 : 1;
});
echo '<pre>';print_r($c);echo '</pre>';die();
...
}
You don't need to use different sortById
method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With