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"

  • You starting with JSON? How do you get that structure? If coming from JSON see `$assoc` argument of `json_decode`. – ficuscr May 23 '19 at 21:06
  • 3
    To start `return $a->title - $b->title;` – AbraCadaver May 23 '19 at 21:06
  • 1
    Possible duplicate of [PHP Sort function for sorting an array of objects](https://stackoverflow.com/questions/3749071/php-sort-function-for-sorting-an-array-of-objects) – ficuscr May 23 '19 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 –  May 23 '19 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. –  May 23 '19 at 21:12
  • Ah thanks ficuscr the getFn function comment from your link worked perfectly, thanks! I tried 5 other old answers but none worked - but yours did thank you! –  May 23 '19 at 21:14
  • Possible duplicate of [How to sort an array of associative arrays by value of a given key in PHP?](https://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php) – miken32 May 23 '19 at 22:52

0 Answers0