0

I'm trying to sort a multi-dimensional array by one of the values (title) in alphabetical order A-Z, but get an error: Cannot use object of type stdClass as array

I'm using php 7.1

My array is $data and looks like this:

[0] => stdClass Object
        (
            [id] => 1 
            [title] => Manager - Chicago Branch
    )

[1] => stdClass Object
        (
            [id] => 2 
            [title] => Manager - New York Branch
    )

[2] => stdClass Object
        (
            [id] => 3 
            [title] => Manager - Detroit Branch
    )

I've tried the follow, with $jobs being the array and "title" being the field I'm trying to sort by:

function cmp($a, $b) {
        return $a["title"] - $b["title"];
}
usort($jobs, "cmp");

I expected the array to sort (without any data being lost) alphabetically sorted by the "title" value, but instead I get the error: "Cannot use object of type stdClass as array"

7
  • You starting with JSON? How do you get that structure? If coming from JSON see $assoc argument of json_decode. Commented May 23, 2019 at 21:06
  • 3
    To start return $a->title - $b->title; Commented May 23, 2019 at 21:06
  • 1
    Possible duplicate of PHP Sort function for sorting an array of objects Commented May 23, 2019 at 21:09
  • So the array is coming from a component within Joomla, so I don't believe it's starting from json format as far as I know Commented May 23, 2019 at 21:10
  • AbraCadaver I tried your change, I don't get the error anymore, but it also does not sort alphabetically or at all according to the ouput. Commented May 23, 2019 at 21:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.