首页  >  文章  >  后端开发  >  PHP如何按对象字段对对象数组进行排序?(代码实例)

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

藏色散人
藏色散人原创
2019-03-19 11:08:348467浏览

本篇文章就是将给大家介绍在PHP中,按对象字段对对象数组排序的实现方法。

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

给定一个对象数组,我们按对象和给定字段对数组排序。

方法:

usort()函数是PHP中内置的函数,用于使用给定的比较器函数对元素数组进行有条件的排序。usort()函数还可以用于按对象字段对对象数组排序。调用usort()函数,第一个参数作为对象数组,第二个参数作为比较器函数,必须在此基础上比较两个数组对象。

PHP代码示例:

<?php 
  
$gfg_array = array( 
    array( 
        &#39;score&#39; => &#39;100&#39;, 
        &#39;name&#39; => &#39;Sam&#39;, 
        &#39;subject&#39; => &#39;Data Structures&#39;
    ), 
    array( 
        &#39;score&#39; => &#39;50&#39;, 
        &#39;name&#39; => &#39;Tanya&#39;, 
        &#39;subject&#39; => &#39;Advanced Algorithms&#39;
    ), 
    array( 
        &#39;score&#39; => &#39;75&#39;, 
        &#39;name&#39; => &#39;Jack&#39;, 
        &#39;subject&#39; => &#39;Distributed Computing&#39;
    ) 
); 
  
class geekSchool {  
    var $score, $name, $subject; 
    
    public function geekSchool($data) { 
        $this->name = $data[&#39;name&#39;]; 
        $this->score = $data[&#39;score&#39;]; 
        $this->subject = $data[&#39;subject&#39;]; 
    } 
} 
  
function data2Object($data) { 
    $class_object = new geekSchool($data); 
    return $class_object; 
}  

function comparator($object1, $object2) { 
    return $object1->score > $object2->score; 
} 
  
$school_data = array_map(&#39;data2Object&#39;, $gfg_array); 
  
print("原始对象数组:\n"); 
  
print_r($school_data); 
  
usort($school_data, &#39;comparator&#39;); 
  
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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn