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);
usort()?