1

I would like to sort by two criteria in an array. The first criterion is the second category and title.

I tried using usort () but it does not work.

Is there a php function to do this?

My original array:

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
    )
)

I would like this:

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
    )               
)

Thanks.

I have not tried much because I found a method:

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;
}
}

But it also works with 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);
2
  • Try this nl1.php.net/array_multisort Commented Mar 15, 2014 at 11:11
  • 1
    What comparison function did you use with usort()? Commented Mar 15, 2014 at 11:13

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you it also works as you indicate. I added a supplement to indicate how I was going because I did not search enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.