【问题标题】:How to access assorted decoded Json arrays in PHP?如何在 PHP 中访问各种解码的 Json 数组?
【发布时间】:2019-02-18 06:26:28
【问题描述】:

我有以下格式的 JSON 数据:

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

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

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

它打印1

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

解析错误:语法错误,意外的'[',需要标识符(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));

【问题讨论】:

  • 那个数组太多了:array(myjsondatas)。让它$decode = json_decode($myjsondatas);
  • 我想myjsondatas前面缺少的$只是一个错字..
  • 对不起,我试图用一个词来表达我的 json 数据。
  • 删除数组后(我的第一条评论),那么正确的语法是echo $decoded->{'0'}->pr;
  • 无论如何我做了你的语法@Jeff。一切似乎都在工作。感谢你们所有人的耐心教导我。

标签: php arrays json associative-array


【解决方案1】:

索引是"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' => 字符串'2'(长度=1)

public 'rfq' => 字符串'2'(长度=1)

myjsondata->0->pr 给出:2

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多