sort an object array in php

后端 未结 3 1560
予麋鹿
予麋鹿 2021-01-29 00:01

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 t

相关标签:
3条回答
  • 2021-01-29 00:09

    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;
        });
    
    0 讨论(0)
  • 2021-01-29 00:15

    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;
    }
    
    0 讨论(0)
  • 2021-01-29 00:30

    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);
    });
    
    0 讨论(0)
提交回复
热议问题