简体   繁体   中英

looping over all elements in JSON response PHP

After making a cURL call, I get a JSON response back as follows, already decoded as a string.

{
  "AAPL": {
    "fundamental": {
      "symbol": "AAPL",
      "high52": 229.67,
      "low52": 149.16,
  }
}

If I want to loop over all elements in 'fundamental,' what would be the best loop to use for this in PHP? I have tried the foreach method, but I was getting an illegal character use message .

I also get the error: Undefined property: stdClass::$fundamental when trying:

$json_new = json_decode($json);
echo $json_new->fundamental;

The current foreach :

foreach ($json_new as $val){
     echo $val->fundamental;
}

Step-1: decode JSON to array

$arr = json_decode($json, true);

Step-2: loop

foreach ($arr['AAPL']['fundamental'] as $key => $val) {
  echo $key . ' = ' . $val . PHP_EOL;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM