JSON文件:
{
"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'];
为什么我无法获得符号? 我怎样才能获得所有符号值? 谢谢!
答案 0 :(得分:3)
在您的情况下,$stocks['stock']
是您要循环的数组。我更改了变量名称以了解循环:
$stocks = json_decode($json, true);
foreach($stocks['stock'] AS $stock){
echo $stock['symbol'] ."<br>";
}
返回
AVGO
CBS
答案 1 :(得分:1)
你必须使用$jsona['stock'][0]['symbol']
因为stock包含一个数组,所以你必须指定你正在访问的数组的哪个元素。然后,您可以使用foreach循环遍历$jsona['stock']
数组的每个元素。
答案 2 :(得分:1)
&#34; stock&#34;的价值是一个数组。所以你可以这样做:
echo $jsona['stock'][0]['symbol'];
echo $jsona['stock'][1]['symbol'];
或循环播放:
foreach ($jsona['stock'] as $stock) {
echo "Symbol: {$stock['symbol']}\n";
echo "Name: {$stock['name']}\n";
echo "Sector: {$stock['sector']}\n\n";
}
产生:
Symbol: AVGO
Name: Broadcom Ltd.
Sector: Technology
Symbol: CBS
Name: CBS Corp.
Sector: Cyclicals