0

HI i want to sort an array of objects , it is in the form of array which has objects and each objects has key,value , i want to sort the objects based on value, the problem is the values contains the numbers which have spaces in between, and some are empty numbers too, so I am not able to sort it using usort any help would be appreciated.

here's a code snippet

array(4) {
  [0]=>
  object(stdClass)#308 (2) {
    ["key"]=>
    string(2) "AF"
    ["value"]=>
    string(3) "093"
  }
  [1]=>
  object(stdClass)#306 (2) {
    ["key"]=>
    string(2) "AL"
    ["value"]=>
    string(3) "355"
  }
  [2]=>
  object(stdClass)#304 (2) {
    ["key"]=>
    string(2) "DZ"
    ["value"]=>
    string(3) "213"
  }
  [3]=>
  object(stdClass)#302 (2) {
    ["key"]=>
    string(2) "AS"
    ["value"]=>
    string(5) "1 684"
  }

}

I want the result to be sorted based on the value.

Leri
  • 12,367
  • 7
  • 43
  • 60
user1490244
  • 209
  • 1
  • 3
  • 7

3 Answers3

1

Try following (I assume that you want to ignore spaces in numbers):

uasort($yourArray, function($a, $b)
    {
        $a->value = str_replace(' ', '', $a->value);
        $b->value = str_replace(' ', '', $b->value);
        return (int)$a->value - (int)$b->value;
    });
Leri
  • 12,367
  • 7
  • 43
  • 60
0

You can use

usort($list, function ($a, $b) {
    $a = filter_var($a->value,FILTER_SANITIZE_NUMBER_INT);
    $b = filter_var($b->value,FILTER_SANITIZE_NUMBER_INT);
    return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
});
Baba
  • 94,024
  • 28
  • 166
  • 217
-1

Of course you can use usort, you simply need to pre-process the values inside the usort compare function prior to comparing. I'm assuming you want to remove the spaces, treat empty numbers as zeros, and ignore leading zeros. Assuming all that your custom compare function might look something like this:

function my_sort($obja, $objb)
{
   $a = (int)(str_replace(" ", "", $obja->value));
   $b = (int)(str_replace(" ", "", $objb->value));
   if ($a == $b) return 0;
   return ($a > $b) ? -1 : 1;
}
MeLight
  • 5,454
  • 4
  • 43
  • 67