PHP按对象字段对对象数组进行排序的方法
发布时间:2020-08-21 11:52:59
来源:亿速云
阅读:93
作者:小新
这篇文章主要介绍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按对象字段对对象数组进行排序的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!