Reputation: 1070
I am trying to sort an array by a non standard sorting of an inner value, but then when other values are equal, retain their order. So I do this:
$articles[0]['name']='Article 1';
$articles[0]['grouping']='';
$articles[1]['name']='Article 2';
$articles[1]['grouping']='Item group';
$articles[2]['name']='Article 3';
$articles[2]['grouping']='';
$articles[3]['name']='Article 4';
$articles[3]['grouping']='Item group';
$articles[4]['name']='Article 5';
$articles[4]['grouping']='';
function cmpBySort($a, $b) {
return strcmp($a["grouping"], $b["grouping"]);
}
usort($articles, 'cmpBySort');
foreach ($articles as $article){
echo $article['name'].' - '.$article['grouping'].'<br>';
}
Which sort likes so:
Article 5 -
Article 1 -
Article 3 -
Article 2 - Item group
Article 4 - Item group
But I want to achieve Article 2 - Item group Article 4 - Item group Article 1 - Article 3 - Article 5 -
Noticing that I want the blanks at the end, and when equivalent, then order by the article name (so 1,3,5 instead of 5,1,3)
Hope someone is an array wizz that can help figure this out! Thanks! Scott
Upvotes: 0
Views: 102
Reputation: 10686
Try:
function cmpBySort($a, $b) {
if (strcmp($a["grouping"], $b["grouping"]) == 0) {
return strcmp($a["name"], $b["name"]);
}
return -strcmp($a["grouping"], $b["grouping"]);
}
Upvotes: 4