如何根据多个条件对数组进行排序?

时间:2014-03-15 11:09:12

标签: php arrays sorting object

我想按数组中的两个条件排序。 第一个标准是第二个类别和标题。

我尝试使用usort()但它不起作用。

是否有php功能可以执行此操作?

我原来的阵列:

Array
(
    [0] => stdClass Object
    (
        [id] => 1
        [category] => cat1
        [title] => title1
    )
[1] => stdClass Object
    (
        [id] => 3
        [category] => cat2
        [title] => z
    )       
[2] => stdClass Object
    (
        [id] => 2
        [category] => cat1
        [title] => title2
    )
[3] => stdClass Object
    (
        [id] => 4
        [category] => cat2
        [title] => a
    )
)

我想这样:

Array
(
    [0] => stdClass Object
    (
        [id] => 1
        [category] => cat1
        [title] => title1
    )
[1] => stdClass Object
    (
        [id] => 2
        [category] => cat1
        [title] => title2
    )       
[2] => stdClass Object
    (
        [id] => 4
        [category] => cat2
        [title] => a
    )
[3] => stdClass Object
    (
        [id] => 3
        [category] => cat2
        [title] => z
    )               
)

感谢。

我没有尝试太多因为我找到了一个方法:

usort($object, 'sort');
function sort($a,$b){
if($a->category == $b->category){
    if($a->title == $b->title){
        return 0;
    }else{
        return ($a->title < $b->title) ? -1 : 1;
    }
}else{
    return ($a->category < $b->category) ? -1 : 1;
}
}

但它也适用于multisort():

foreach ($object as $sort_key => $sort_row) {
    $category[$sort_key]  = $sort_row->acls_category;
    $title[$sort_key] = $sort_row->acls_title;
}
array_multisort($category, SORT_ASC, $title, SORT_ASC, $object);

1 个答案:

答案 0 :(得分:1)

$o1 = new stdClass;
$o1->id = 1;
$o1->category = 'cat1';
$o1->title = 'title1';

$o2 = new stdClass;
$o2->id = 3;
$o2->category = 'cat2';
$o2->title = 'z';

$o3 = new stdClass;
$o3->id = 2;
$o3->category = 'cat1';
$o3->title = 'title2';

$o4 = new stdClass;
$o4->id = 4;
$o4->category = 'cat2';
$o4->title = 'a';

$arr = array($o1, $o2, $o3, $o4);

usort($arr, function($a, $b) {
    $catCmp = strcmp($a->category, $b->category);

    if ($catCmp) {
        return $catCmp;
    }

    return strcmp($a->title, $b->title);
});

var_dump($arr);