如何在PHP中访问各种解码的Json数组?

问题描述 投票:1回答:1

我有以下格式的JSON数据:

{
   "pr":"1",
   "0":{
      "pr":"2",
      "rfq":"2"
   },
   "1":{
      "pr":"3",
      "rfq":"3"
   }
}

我尝试解码这个JSON,当我访问第一个数据时:

$decode = json_decode( array(myjsondatas));
echo $decode->pr;

它打印1

但是当我尝试使用这种语法0访问数组1$decode->[0]->pr;时,它给了我一个错误:

解析错误:语法错误,意外的'[',期待标识符(T_STRING)或变量(T_VARIABLE)或'{'或'$'

如何从数组01访问数据?

PS:这就是我如何构建我的json数据'myjsondatas'不是变量

$arr = array("pr" => '2' ,  "rfq" => '2');
$arr1 = array("pr" => '3' ,  "rfq" => '3');

$json = json_encode(array("pr" => '1', $arr, $arr1));
php arrays json associative-array
1个回答
0
投票

该指数是"0",而不是0

您可以使用变量来存储索引,如下所示:

$myjsondata = '{
    "pr":"1",
    "0":{
        "pr":"2",
        "rfq":"2"
    },
    "1":{
        "pr":"3",
        "rfq":"3"
    }
}';

$decode = json_decode($myjsondata);

$someIndex = "0";

var_dump($decode->$someIndex);

echo "myjsondata->0->pr gives : " . $decode->$someIndex->pr;

输出:

对象(stdClass的)[2]

public'pr'=> string'2'(长度= 1)

public'rfq'=> string'2'(长度= 1)

Mizasandar-> 0-> Geeves at:2

© www.soinside.com 2019 - 2024. All rights reserved.