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

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

提交回复
热议问题