-1

Please note that I have read similar questions on this site but none worked for me and this seem unique at least for now/to me.

I have the following array;

[{"advert_id":"advert1"},{"advert_id":"advert2"},{"advert_id":"advert3"},{"advert_id":"advert4"},{"advert_id":"advert5"},{"advert_id":"advert6"},{"advert_id":"advert7"}]

I actually got the data when I fetch information from database with Laravel $adverts = Advert::select('advert_id')->get();

How can I randomly select an element from it?

I tried using array_rand($adverts) but had errors (array_rand() expects parameter 1 to be array, object given )

Diamond
  • 608
  • 7
  • 23
  • 4
    `json_decode($json, true);` – Darren Jun 18 '14 at 08:47
  • 2
    That is not a PHP array, you're using JSON notation. The error you give suggests that you converted it to an object at some point. You probably used `json_decode` for that. As Darren pointed out, you should set the second argument to `true`. – jornane Jun 18 '14 at 08:49
  • Alternatively, you may try `$adverts = get_object_vars($adverts)`, to convert the object to an array. – jornane Jun 18 '14 at 08:51
  • Ok, lemme try that out – Diamond Jun 18 '14 at 08:51
  • Wow, alot of vote down but I don't mind cause `json_decode($json, true);` worked for me. Thanks to @Darren for the answer and @Jorn for the explaination – Diamond Jun 18 '14 at 09:19

1 Answers1

1

Here's a proper answer so that you can hopefully mark it correct, allowing others to find it as well.

You're referencing an array but parsing an object. Now using json_decode() as below and parsing the second parameter, you explicitly ask for an array in return instead of an object.

json_decode($array, true);
Darren
  • 13,050
  • 4
  • 41
  • 79