Search code examples
phpstrcmpusort

Sorting XML results with PHP usort + strcmp? (integers)


I am trying to order the results of an AJAX call on my page by comparing the numerical value of one of the fields in the XML object. Basically, it is a product popularity ranking where the higher the number is, the more popular it is.

I almost have it working, except strcmp only compares the first digit, so the order goes something like this currently: 1, 12, 15, 19, 2, 21, 24, 3, 34, 36, 39, 5, 52, 56

How can I modify this code so that the numbers are ordered lowest to highest regardless of how many digits there are?

$products = array();
foreach($xml->Products as $product) {
    $products[] = $product;
};

// Sort results based on popularity
usort ($products, function($a, $b) {
    return strcmp($a->ProductPopularity, $b->ProductPopularity);
});

Thank you!


Solution

  • Cast as integers and do a normal comparison.

     usort($myArray, function($a, $b) {
          if((int)$a->ProductPopularity==(int)$b->ProductPopularity) return 0;
          return (int)$a->ProductPopularity < (int)$b->ProductPopularity?1:-1;
     });