In this article we will show you the solution of PHP sort array of objects, in PHP, arrays come in handy when programmers store data in variables. By making particular categories and putting all the values associated with those categories in a list, you may organize them.
There are times when arrays may contain too many values, and they may become difficult to manage.
The PHP sort array functions are supposed to simplify the manipulation of arrays so that you can organize them as you want.
We will now discuss the idea of how to sort an array of objects in php with an example.
Step By Step Guide On PHP Sort Array Of Objects :-
<?php function orderBy($items, $attr, $order) { $sortedItems = []; foreach ($items as $item) { $key = is_object($item) ? $item->{$attr} : $item[$attr]; $sortedItems[$key] = $item; } if ($order === 'desc') { krsort($sortedItems); } else { ksort($sortedItems); } return array_values($sortedItems); } print_r(orderBy( [ ['id' => 2, 'name' => 'Red'], ['id' => 3, 'name' => 'Black'], ['id' => 1, 'name' => 'Green'] ], 'id', 'desc' )); ?>
- As a first step, the code defines a function called 'orderBy'. This function takes three parameters: $items (array), $attr (string), and $order (string).
- As part of the function, an empty array named $sortedItems is created in order to store the sorted items.
- Iterating over each item in $items is accomplished by using a foreach loop. To access the values of the corresponding attributes in each item, the $attr value is used as a key inside the loop. Array elements whose values represent attributes are stored in $sortedItems array elements whose keys represent attribute values and whose values represent item values.
- After all items have been handled, the code checks the $order argument. When the $sortedItems array has the 'desc' key (descending order), the krsort() function is used to sort it descendingly. The ksort() function sorts the array in ascending order if its value is 'asc' (for ascending order).
- The array_values() function is used to revert the keys to consecutive integers before returning the values from the $sortedItems array.
- A descending order sort is performed with an example array of items and the attribute 'id' at the end of the code to call the orderBy function. In this case, the print_r() function is used to display the result.
Conclusion :-
As a result, we have successfully learned how to sort an array of objects in php with an example.
PHP provides inbuilt functions that make sorting PHP arrays easy. An array can be sorted by key or value, in numeric, alphabetical, ascending, descending, or ascending order in PHP.
An associative array is the only array for which some functions can be applied.
I hope this article on PHP sort array of objects helps you and the steps and method mentioned above are easy to follow and implement.