How to use usort in Laravel with example
In this article I will Guide you how we can use usort in Laravel to sort array, I will sort array datewise in laravel.
Before moving forward Let’s know what usort is .
PHP comes with a number of built-in functions that are used to sort arrays in an easier way. Here, we are going to discuss a new function usort(). The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
Syntax:
boolean usort( $array, "function_name");
Parameters: This function accepts two parameters as shown in the above syntax and are described below:
- $array: This parameter specifies the array which u want to sort.
- function_name : This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two arguments are equal, then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
Return Value: This function returns the boolean type of value. It returns TRUE in case of success and FALSE in case of failure.
Now let’s see how we can use usort in laravel by viewing below example.
public function getStudent()
{
$data[] = [
'id'=> $v['id'],
'class' => $key,
'time_to' => date("h:i a",strtotime($v['time_to'])),
'time_from' => date("h:i a",strtotime($v['time_from'])),
'subject' => $v['subject'],
'class_date' => $v['class_date'],
'no_of_student_present'=> $userJoined,
'no_of_student_absent'=> $userCount[$key] - $userJoined,
];
}
dd($data);
I will try to show with the dynamic pattern, later I will show you statically. If I will dd my code it will return value like the below one.
Now I will write the code to sort the data in a datewise manner
usort($data, array( $this, 'sortDate' ));
// here data is array and sortDate is another function
Now I will write the logic for sortDate
public function sortDate($a, $b)
{
if (strtotime($a['class_date']) == strtotime($b['class_date'])) return 0;
return (strtotime($a['class_date']) > strtotime($b['class_date'])) ?-1:1;
}
You can see the result in the below image.
If you compare both the image you will get to know the data with the latest date is coming first.
In the below code I will show with the static array.
public function sortArray()
{
$arr= array(2, 9, 1, 3, 5);
usort($arr, array( $this, 'sortNumber' ));
}
public function sortNumber()
{
// If $x is equal to $y it returns 0
if
($x== $y)
return
0;
// if x is less than y then it returns -1
// else it returns 1
if
($x
< $y)
return
-1;
else
return
1;
}
Read Also: Find in set in laravel
I hope you like the above article, now you will understand how you can use usort in Laravel.
2 Comments