使用usort和自定义比较函数的多维数组/对象排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用usort和自定义比较函数的多维数组/对象排序相关的知识,希望对你有一定的参考价值。
/**
*
* EXAMPLE #1
*
* sort array of objects based on specified attribute values
* in this case "lastname", followed by "firstname"
*
**/
$person1 = (object
) array('lastname' => 'Jones', 'firstname' => 'Michael', 'Degree' => 'AAA'); $person2 = (object
) array('lastname' => 'Adams', 'firstname' => 'Zach', 'Degree' => 'BB'); $person3 = (object
) array('lastname' => 'Smith', 'firstname' => 'Jim', 'Degree' => 'CCC'); $person4 = (object
) array('lastname' => 'Adams', 'firstname' => 'Tom', 'Degree' => 'DD');
$array_to_be_sorted = array( $person1, $person2, $person3, $person4);
echo "Before";
echo "<pre>";
echo "</pre>";
echo "<br /><br />";
function alpha_sort($a, $b) {
if ($a->lastname == $b->lastname) {
return strnatcmp($a->firstname, $b->firstname); }
return strnatcmp($a->lastname, $b->lastname); }
usort($array_to_be_sorted, "alpha_sort");
echo "After";
echo "<pre>";
echo "</pre>";
?>
<?php
/**
*
* EXAMPLE #2
*
* sort array of arrays based on specified array keys
* in this case "lastname", followed by "firstname"
*
**/
$array_to_be_sorted = array( array('lastname' => 'Jones', 'firstname' => 'Michael'), array('lastname' => 'Adams', 'firstname' => 'Zach'), array('lastname' => 'Smith', 'firstname' => 'Jim'), array('lastname' => 'Adams', 'firstname' => 'Tom') );
function alpha_sort($a, $b) {
if ($a['lastname'] == $b['lastname']) {
return strnatcmp($a['firstname'], $b['firstname']); }
return strnatcmp($a['lastname'], $b['lastname']); }
usort($array_to_be_sorted, "alpha_sort");
echo "<pre>";
echo "</pre>";
?>
以上是关于使用usort和自定义比较函数的多维数组/对象排序的主要内容,如果未能解决你的问题,请参考以下文章
usort() 自定义排序
使用 PHP usort() 通过用户自定义的比较函数对数组进行排序
PHP多维数组的排序问题
通过继续值对Usort排序多维数组
sort方法和自定义比较器的写法
关于回调函数 usort() uksrot() sort() 介绍简介实验是从小到大排序