0

JSON file:

{
    "stock": [
            {
                "symbol": "AVGO",
                "name": "Broadcom Ltd.",
                "sector": "Technology",
                "industry": "Semiconductors",
                "SCTR": "97.8",
                "delta": "2.5",
                "close": "154.97",
                "vol": "2297509"
            }, 
            {
                "symbol": "CBS",
                "name": "CBS Corp.",
                "sector": "Cyclicals",
                "industry": "Entertainment",
                "SCTR": "92.3",        
                "delta": "-3.6",
                "close": "53.58",
                "vol": "4045416"
            }
       ]
}

PHP:

$jsona = json_decode($json, true);
echo $jsona['stock']['symbol'];

Why I can't get the symbol? And how can I get all symbol value? Thanks!

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Fireghost
  • 129
  • 2
  • 12

3 Answers3

1

You have to use $jsona['stock'][0]['symbol'] because stock contains an array so you have to specify which element of the array you're accessing. You can then use a foreach loop to loop through each element of the $jsona['stock'] array.

Nathan Bierema
  • 1,813
  • 2
  • 14
  • 24
1

In your case $stocks['stock'] is the array you want to loop through. I changed the variable names to make some sense of the loop:

$stocks = json_decode($json, true);
foreach($stocks['stock'] AS $stock){
    echo $stock['symbol'] ."<br>";
}

Returns

AVGO

CBS

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
1

The value of "stock" is an array. So you can either do:

echo $jsona['stock'][0]['symbol'];
echo $jsona['stock'][1]['symbol'];

or loop through them:

foreach ($jsona['stock'] as $stock) {
    echo "Symbol: {$stock['symbol']}\n";
    echo "Name: {$stock['name']}\n";
    echo "Sector: {$stock['sector']}\n\n";
}

which produces:

Symbol: AVGO
Name: Broadcom Ltd.
Sector: Technology

Symbol: CBS
Name: CBS Corp.
Sector: Cyclicals
David White
  • 1,763
  • 2
  • 16
  • 27
  • It's work, great! But I still cannot get the idea if the JSON changed to
    [ { "symbol": "AVGO", "name": "Broadcom Ltd." }, { "symbol": "CBS", "name": "CBS Corp." } ]
    – Fireghost Apr 08 '16 at 17:25
  • @Fireghost: Read the duplicate question. It teaches you what these structures really mean and how to access them in a general way, not just specific to your data. That will hopefully allow you to apply that knowledge to differently structured data. – Felix Kling Apr 08 '16 at 17:48