当前位置:Gxlcms > PHP教程 > PHP如何按对象字段对对象数组进行排序?(代码实例)

PHP如何按对象字段对对象数组进行排序?(代码实例)

时间:2021-07-01 10:21:17 帮助过:30人阅读

本篇文章就是将给大家介绍在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如何按对象字段对对象数组进行排序?(代码实例)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行