4

I'm trying to read the returned json below but i keep getting errors.

Cannot use object of type stdClass as array

I'm fetching the json via curl and then json_decode($data);

foreach($array as $a)
{
   switch($a)
   {
       case"BTC":
         //do something
       case"ETH":
         //do something


   }

}

Url :

https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,LTC,XMR,XRP,DASH,ZEC&tsyms=USD

Var Dump Results :

object(stdClass)#405 (6) { ["BTC"]=> object(stdClass)#404 (1) { ["USD"]=> float(13571.4) } ["LTC"]=> object(stdClass)#406 (1) { ["USD"]=> float(235.57) } ["XMR"]=> object(stdClass)#407 (1) { ["USD"]=> float(399.11) } ["XRP"]=> object(stdClass)#408 (1) { ["USD"]=> float(1.83) } ["DASH"]=> object(stdClass)#409 (1) { ["USD"]=> float(1000.25) } ["ZEC"]=> object(stdClass)#410 (1) { ["USD"]=> float(658.29) } } 
J.Adams
  • 133
  • 7

2 Answers2

5

Decode as Associative Array

For decoding JSON as an array, you have to pass assoc parameter to the json_decode function.

When the assoc parameter is TRUE, returned objects will be converted into associative arrays.

Refer PHP Docs for more information regarding the function.

Example Code

json_decode($data, true);
Community
  • 1
  • 1
RamC
  • 1,287
  • 1
  • 11
  • 15
0

There is a second parameter to json_decode which allows you to parse json data as associative arrays. try:

json_decode($data, true);
Ataur Rahman
  • 1,671
  • 14
  • 12