本篇文章就是將介紹給大家在PHP中,依物件欄位對物件陣列排序的實作方法。
給定一個物件數組,我們按物件和給定欄位對數組排序。
方法:
usort()函數是PHP中內建的函數,用於使用給定的比較器函數對元素數組進行有條件的排序。 usort()函數也可以用於按物件欄位對物件數組排序。呼叫usort()函數,第一個參數作為物件數組,第二個參數作為比較器函數,必須在此基礎上比較兩個數組物件。
PHP程式碼範例:
<?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);
輸出:
原始对象数组: 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 ) )
相關推薦:《PHP教學 》
本篇文章就是關於在PHP中按物件欄位對物件陣列進行排序的方法介紹,簡單易懂,希望對需要的朋友有所幫助!
以上是PHP如何依物件欄位對物件數組進行排序? (程式碼實例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!