Home > Article > Backend Development > How to sort object array by object field in PHP? (code example)
This article will introduce to you the implementation method of sorting object arrays by object fields in PHP.
Given an array of objects, we sort the array by objects and given fields.
Method:
usort() function is a built-in function in PHP that is used to conditionally sort an array of elements using a given comparator function. The usort() function can also be used to sort an object array by object fields. When calling the usort() function, the first parameter is used as the object array, and the second parameter is used as the comparator function. The two array objects must be compared on this basis.
PHP code example:
<?php $gfg_array = array( array( 'score' => '100', 'name' => 'Sam', 'subject' => 'Data Structures' ), array( 'score' => '50', 'name' => 'Tanya', 'subject' => 'Advanced Algorithms' ), array( 'score' => '75', 'name' => 'Jack', 'subject' => 'Distributed Computing' ) ); class geekSchool { var $score, $name, $subject; public function geekSchool($data) { $this->name = $data['name']; $this->score = $data['score']; $this->subject = $data['subject']; } } function data2Object($data) { $class_object = new geekSchool($data); return $class_object; } function comparator($object1, $object2) { return $object1->score > $object2->score; } $school_data = array_map('data2Object', $gfg_array); print("原始对象数组:\n"); print_r($school_data); usort($school_data, 'comparator'); print("\n对象数组排序:\n"); print_r($school_data);
Output:
原始对象数组: Array ( [0] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) [1] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [2] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) ) 对象数组排序: Array ( [0] => geekSchool Object ( [score] => 50 [name] => Tanya [subject] => Advanced Algorithms ) [1] => geekSchool Object ( [score] => 75 [name] => Jack [subject] => Distributed Computing ) [2] => geekSchool Object ( [score] => 100 [name] => Sam [subject] => Data Structures ) )
Related recommendations: "PHP Tutorial 》
This article is an introduction to the method of sorting object arrays by object fields in PHP. It is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to sort object array by object field in PHP? (code example). For more information, please follow other related articles on the PHP Chinese website!