How do I sort a multidimensional array with stdClass Objects by values of a key?

后端 未结 3 901
暖寄归人
暖寄归人 2021-01-06 06:59

Yes, I have searched and tried many techniques, but nothing seems to work. Here is my array:

Array
(
    [0] => stdClass Object
        (
            [id]         


        
相关标签:
3条回答
  • 2021-01-06 07:51

    You should use usort...

    So you define a function that compares two objects (by the name field) and then run usort on the array, passing in the function as the second argument.

    Something like this:

    function cmp($a, $b)
    {
        if ($a["name"] == $b["name"]) {
            return 0;
        }
        return ($a["name"] < $b["name"]) ? -1 : 1;
    }
    
    usort ($my_array, "cmp");
    var_dump($my_array);
    

    Hope that helps!

    Ben

    0 讨论(0)
  • 2021-01-06 07:58

    You're almost right, but $row[$col] tries to access the objects like an array. You want something like $row->{$col} instead. Here's a simpler, working example:

    $db = array(
      0 => (object) array('name' => 'Business3'),
      1 => (object) array('name' => 'Business2'),
      2 => (object) array('name' => 'Business1')
    );
    
    $col  = 'name';
    $sort = array();
    foreach ($db as $i => $obj) {
      $sort[$i] = $obj->{$col};
    }
    
    $sorted_db = array_multisort($sort, SORT_ASC, $db);
    
    print_r($db);
    

    Outputs:

    Array
    (
        [0] => stdClass Object
            (
                [name] => Business1
            )
    
        [1] => stdClass Object
            (
                [name] => Business2
            )
    
        [2] => stdClass Object
            (
                [name] => Business3
            )
    
    )
    
    0 讨论(0)
  • 2021-01-06 08:00
    usort($array, function($a, $b) {
        return strcmp($a->name, $b->name);
    });
    
    0 讨论(0)
提交回复
热议问题