- Php php array of objects sort by property
- PHP sort array of objects by two properties
- Sort array by object property in PHP?
- Jan 2016 update
- Jan 2015 update
- Original Notes from 2009
- Sort array of objects by property value inside a function [duplicate]
- Php order by object property
- PHP Function Based
- PHP Date Based
- PHP String Based
- PHP Class Based
- PHP JSON Based
- PHP File Systems Based
Php php array of objects sort by property
Solution: 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 An added benefit of having Heaps is being able to use their comparison function for callbacks to other sorting functions, like .
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);
Why don’t you use array_multisort ? http://php.net/manual/de/function.array-multisort.php
$data = //your array //Create independent arrays foreach ($data as $row) < foreach ($row as $key =>$value)< $[] = $value; //Creates $tab_option_name_selector, $fieldtype and $order array //in order to use them as independent arrays in array_multisort. > > array_multisort($tab_option_name_selector, SORT_ASC, $order, SORT_ASC, $data); //$data sorted as expected. echo "
"; print_r($data); echo "";
An example for unlimited number of properties:
$data = [ (object)['volume' => '1', 'edition' => '1'], (object)['volume' => '2', 'edition' => '1'], (object)['volume' => '3', 'edition' => '10'], (object)['volume' => '3', 'edition' => '50'], (object)['volume' => '3', 'edition' => '20'], (object)['volume' => '4', 'edition' => '3'], ]; // sorting list by properties $sorting = ['volume' => SORT_DESC, 'edition' => SORT_ASC]; $arrays = []; foreach ($sorting as $key => $sort) < $column = array_column($data, $key); if (!empty($column)) < $arrays[] = $column; $arrays[] = $sort; >> if (!empty($arrays)) < $arrays[] = $data; if (!array_multisort(. $arrays)) < var_dump('some error'); die(); >// get last array, that is the sorted data $data = ($arrays[array_key_last($arrays)]); >
Example partially from php.net — array_multisort
Sorting an array of an array of objects in PHP by key value, A way to do this is to separate the value array from the array of objects, and thus, creating two
Sort array by object property in PHP?
The question was concerned about the inefficiency of using usort because of the overhead of calling the comparison callback. This answer looks at the difference between using the built-in sort functions and a non-recursive quicksort implementation.
The answer changed over time as PHP evolved since 2009, so I’ve kept it updated. The older material, while no longer relevant, is still interesting though!
TL;DR: as of php 7.0.1, a non-recursive quicksort is no longer faster than using usort with a callback. This wasn’t always the case, which is why the details below make interesting reading. The real takeaway is that if you benchmark your problem and try alternative approaches, you can come up with surprising results.
Jan 2016 update
Well here we are with php 7.0 released and 7.1 on the way! Finally, for this dataset, the built-in usort is ever-so-slightly faster!
+-----------+------------+------------+------------+------------+------------+ | Operation | HHVM | php7.0.1 | php5.6.3 | 5.4.35 | 5.3.29 | +-----------+------------+------------+------------+------------+------------+ | usort | *0.0445 | *0.0139 | 0.1503 | 0.1388 | 0.2390 | | quicksort | 0.0467 | 0.0140 | *0.0912 | *0.1190 | *0.1854 | | | 5% slower | 1% slower | 40% faster | 15% faster | 23% faster | +-----------+------------+------------+------------+------------+------------+
Jan 2015 update
When I originally answered this in 2009, I compared using usort with a non-recursive quicksort to see if there was a difference. As it turned out, there was significant difference, with the quicksort running 3x faster.
As it’s now 2015, I thought it might be useful to revisit this, so I took code which sorts 15000 objects using usort and quicksort and ran it on 3v4l.org which runs it on lots of different PHP versions. The full results are here: http://3v4l.org/WsEEQ
+-----------+------------+------------+------------+------------+------------+ | Operation | HHVM | php7alpha1 | php5.6.3 | 5.4.35 | 5.3.29 | +-----------+------------+------------+------------+------------+------------+ | usort | *0.0678 | 0.0438 | 0.0934 | 0.1114 | 0.2330 | | quicksort | 0.0827 | *0.0310 | *0.0709 | *0.0771 | *0.1412 | | | 19% slower | 30% faster | 25% faster | 31% faster | 40% faster | +-----------+------------+------------+------------+------------+------------+
Original Notes from 2009
I tried a usort, and sorted 15000 Person objects in around 1.8 seconds.
As you are concerned about the inefficiency of the calls to the comparison function, I compared it with a non-recursive Quicksort implementation. This actually ran in around one third of the time, approx 0.5 seconds.
Here’s my code which benchmarks the two approaches
// Non-recurive Quicksort for an array of Person objects // adapted from http://www.algorithmist.com/index.php/Quicksort_non-recursive.php function quickSort( &$array ) < $cur = 1; $stack[1]['l'] = 0; $stack[1]['r'] = count($array)-1; do < $l = $stack[$cur]['l']; $r = $stack[$cur]['r']; $cur--; do < $i = $l; $j = $r; $tmp = $array[(int)( ($l+$r)/2 )]; // partion the array in two parts. // left from $tmp are with smaller values, // right from $tmp are with bigger ones do < while( $array[$i]->age < $tmp->age ) $i++; while( $tmp->age < $array[$j]->age ) $j--; // swap elements from the two sides if( $i >while( $i $r = $j; >while( $l < $r ); >while( $cur != 0 ); > // usort() comparison function for Person objects function personSort( $a, $b ) < return $a->age == $b->age ? 0 : ( $a->age > $b->age ) ? 1 : -1; > // simple person object class Person < var $age; function __construct($age) < $this->age = $age; > > //---------test internal usort() on 15000 Person objects------ srand(1); $people=array(); for ($x=0; $x $start=microtime(true); usort( $people, 'personSort' ); $total=microtime(true)-$start; echo "usort took $total\n"; //---------test custom quicksort on 15000 Person objects------ srand(1); $people=array(); for ($x=0; $x $start=microtime(true); quickSort( $people ); $total=microtime(true)-$start; echo "quickSort took $total\n";
An interesting suggestion was to add a __toString method to the class and use sort(), so I tried that out too. Trouble is, you must pass SORT_STRING as the second parameter to sort get it to actually call the magic method, which has the side effect of doing a string rather than numeric sort. To counter this, you need to pad the numbers with zeroes to make it sort properly. Net result was that this was slower than both usort and the custom quickSort
sort 10000 items took 1.76266698837 usort 10000 items took 1.08757710457 quickSort 10000 items took 0.320873022079
Here’s the code for the sort() using __toString():
$size=10000; class Person < var $age; function __construct($age) < $this->age = $age; $this->sortable=sprintf("%03d", $age); > public function __toString() < return $this->sortable; > > srand(1); $people=array(); for ($x=0; $x $start=microtime(true); sort( $people, SORT_STRING); $total=microtime(true)-$start; echo "sort($size) took $total\n"
For that specific scenario, you can sort it using the usort() function, where you define your own function to compare the items in the array.
age = $age; > > function personSort( $a, $b ) < return $a->age == $b->age ? 0 : ( $a->age > $b->age ) ? 1 : -1; > $person1 = new Person(14); $person2 = new Person(5); $person3 = new Person(32); $person4 = new Person(150); $person5 = new Person(39); $people = array($person1, $person2, $person3, $person4, $person5); print_r( $people ); usort( $people, 'personSort' ); print_r( $people );
You could either use usort or a heap.
class SortPeopleByAge extends SplMaxHeap < function compare($person1, $person2) < return $person1->age - $person2->age; > > $people = array(new Person(30), new Person(22), new Person(40)); $sorter = new SortPeopleByAge; array_map(array($sorter, 'insert'), $people); print_r(iterator_to_array($sorter)); // people sorted from 40 to 22
Note that the purpose of an Heap is to have an ordered collection at all times and not to replace usort . For large collections (1000+), a heap will be faster and less memory intensive though.
An added benefit of having Heaps is being able to use their comparison function for callbacks to other sorting functions, like usort . You just have to remember that the order for the comparison is reversed, so any comparison done with a Heap will result in reversed order in usort .
// using $people array and $sorter usort($people, array($sorter, 'compare')); print_r($people); // people sorted from 22 to 40
usort is fine for small to medium collections where you will do the sorting once at the end. Of course, you dont have to have a heap to use usort . You can just as well add any other valid callback for the sorting.
Sort array of objects by one property, usort() will sort ascending when the custom function body puts $a data on the left side of the spaceship operator and $b data on the right side.
Sort array of objects by property value inside a function [duplicate]
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');
Sorting an Array of Objects in PHP In a Specific Order, Use usort and provide a custom comparison function which uses the position of the key in your «ordering» array to determine the sort order, e.g. something
Php order by object property
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
PHP Function Based
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
PHP Date Based
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
PHP String Based
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?