Manually Sort Categories PHP usort

时间:2015-07-28 16:49:59

标签: php arrays sorting usort

I have four categories with category IDs 4,6,7,10 that I would like to sort in the following order 4,7,6,10.

I was using usort to do this, and it worked fine before I added category 10. Now I'm adding 10 and the order I get is 10,4,7,6.

A var_dump($categories); before the usort gives the following output:

array(4) {
[0]=>
string(1) "6"
[1]=>
string(1) "4"
[2]=>
string(1) "7"
[3]=>
string(2) "10"
}

I define the order I want the categories in an array, and use that in the usort:

$order = array(4,7,6,10);
            usort($categories, function ($a, $b) use ($order) {
                $pos_a = array_search($a['string'], $order);
                $pos_b = array_search($b['string'], $order);
                return $pos_a - $pos_b;
            });

A var_dump($categories); after the usort gives:

array(4) {
  [0]=>
  string(2) "10"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "7"
  [3]=>
  string(1) "6"
}

I can't figure out why category 10 wants to pop to the beginning of the array instead of the end. Also, I don't know if this is relevant or not but category 10 is the only one with string(2), all others have string(1).

Is the usort as I have it only capable of sorting a limited number of categories? I don't see why it would be, but that's the only thing I can come up with.

Any ideas how I could get the categories sorted in 4,7,6,10 order as it is in the array would be appreciated.

1 个答案:

答案 0 :(得分:1)

your code was not correct. here's it corrected:

$categories = array('6','4','7','10');

var_dump($categories);
$order = array(4,7,6,10);
usort($categories, function ($a, $b) use ($order) {
    $pos_a = array_search($a, $order);
    $pos_b = array_search($b, $order);
    return $pos_a - $pos_b;
});


var_dump($categories);