您好,登錄后才能下訂單哦!
這篇文章主要介紹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按對象字段對對象數組進行排序的方法的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。