我有一个看起来如此的数组:
{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0,
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
从1号开始,我需要抓住current_price。我有一个从两者中抓取它的foreach,但我不确定如何只从第1号获取信息,这是第二块信息--TSBC。有什么想法吗?
答案 0 :(得分:1)
当您在问题中添加json
标记时,我必须注意您提交了无效的json内容。在第一个"股票"中的数字0
之后有一个意想不到的逗号。对象"available_shares": 0,
。
所以,让我们删除那个逗号,如果我们谈论"多维数组"让我们的json字符串以json_decode
函数解码为关联数组:
// $str - is some part of your json string
$str = '{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
}}}';
$arr = json_decode($str, true);
// now we are able to get 'current_price' from the second element of array
var_dump($arr['stocks'][1]['current_price']);
// the output:
float 503.106