Sort array of objects by object fields

后端 未结 19 1552
情书的邮戳
情书的邮戳 2020-11-22 02:28

How can I sort this array of objects by one of its fields, like name or count ?

  Array
(
    [0] => stdClass Object
        (
          


        
19条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 03:20

    You can use usort like this

    If you want to sort by number:

    function cmp($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, "cmp");
    

    Or Abc char:

    function cmp($a, $b)
    {
        return strcmp($a["fruit"], $b["fruit"]);
    }
    
    $fruits[0]["fruit"] = "lemons";
    $fruits[1]["fruit"] = "apples";
    $fruits[2]["fruit"] = "grapes";
    
    usort($fruits, "cmp");
    

    See more: https://www.php.net/manual/en/function.usort.php

提交回复
热议问题