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

后端 未结 3 919
暖寄归人
暖寄归人 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: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
            )
    
    )
    

提交回复
热议问题