0

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.

6
  • usort sorts as much as you pass it. if it's not sorting correctly, then your comparison function isn't working right. Commented Jul 28, 2015 at 16:53
  • 1
    that is your code. it works fine eval.in/407532 Commented Jul 28, 2015 at 16:55
  • what is "string" index you're using? Commented Jul 28, 2015 at 16:56
  • @splash58 you simply turned error reporting off :) Commented Jul 28, 2015 at 16:59
  • 1
    error_reporting(-1) - shows all errors Commented Jul 28, 2015 at 17:05

1 Answer 1

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

1 Comment

Thanks! I thought it needed the ['string'] bit for some reason. Probably just staring at it for too long!

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.