如何将API返回字符串放入数组中

时间:2018-05-17 12:26:50

标签: php

我有一个来自API的字符串,我希望我可以把它放在一个数组中,这样我就可以检查返回的值。

字符串返回示例:

{
  "code":"000",
  "message":"XXX",
  "date":"2018-05-17",
  "hour":"09:16:09",
  "revision":"",
  "server":"XX",
  "content":{
     "nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
  }
}

我需要什么:

echo $string['code'];

Javascript编码命令没有问题。但是我怎么能用PHP做到这一点?

3 个答案:

答案 0 :(得分:1)

首先,您的JSON数据似乎无效( 缺少某些括号 )。它必须是这样的: -

{
    "code": "000",
    "message": "XXX",
    "date": "2018-05-17",
    "hour": "09:16:09",
    "revision": "",
    "server": "XX",
    "content": {
        "nome": {
            "info": "SIM",
            "conteudo": [{
                "field1": "XXXX",
                "field2": "XX"
            }]
        }
    }
}

现在您需要 来解码此JSON数据,然后根据索引获取数据

$array = json_decode($json,true);

echo $array['code'];

输出: - https://eval.in/1005949

答案 1 :(得分:0)

您可以在PHP中将JSON字符串解码为Array。

$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);

var_dump($decodedValue);

答案 2 :(得分:0)

您的示例字符串无效json,您缺少一些右括号。

这应该是正确的方法:

'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'

至于你的问题。在PHP中,您可以轻松使用json_decode

示例:

<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';

$decoded_json = json_decode($json, true);
echo $decoded_json['code'];

您可以看到它有效here