在PHP中将API响应更改为数组

时间:2018-05-25 07:52:04

标签: php api

我有一个API,它会回复我这样的回复。

{
    "logs": [
        [
            "2018-05-22 00:10:16", 
            "Billed"
        ]
    ], 
    "package": "superpremium", 
    "subdate": "2018-05-08 14:18:18", 
    "submedium": "CALL"
}

我试图更改为数组,因此我可以轻松访问它。例如。

$response['subdate']; // echo 2018-05-08 14:18:18
$response['submedium']; // echo CALL
$response['package']; // echo superpremium

和日志应该像

$response['logs'];

日志必须是一个数组,因此我可以使用foreach日志显示数组的所有值,如2018-05-22 00:10:16或" Billed"等

我使用了以下代码,但返回空白屏幕。

json_decode($response, true);
json_decode($response);

4 个答案:

答案 0 :(得分:1)

  

我正在尝试更改为数组

只需将cast加入其中:

$response = (array) json_decode($response);

之后,您可以轻松访问$response['subdate']等。

答案 1 :(得分:0)

使用json_decode($your_response)方法。您的json数据将转换为数组。

像:

$response = json_decode($api_response);

然后您可以访问这些值(通过查看您的数据,似乎您正在获取对象):

$subdate = $response->subdate; // echo 2018-05-08 14:18:18
$submedium = $response->submedium; // echo CALL
$package = $response->package;

答案 2 :(得分:0)

$json_data = json_decode($YourJSONResponse, true);

然后这些将可用:

$json_data["package"]
$json_data["subdate"]
$json_data["submedium"]

答案 3 :(得分:-3)

请更改日期:

"submedium": "CALL"

要:

The input file at this point looks like this:

ABC World News Feed
RSS Data retrieved from https:--abcnews.go.com-abcnews-headlines
05-24 18:48:16    Truckers' strike leads to fuel shortages in Brazil
05-24 18:48:16    The marathon atop the world's deepest lake
           ^^^^^^
           Remove these character positions starting from 12 to 17 
           from each title line, with colon in 12 but not from the heading lines

So the result should look like:

ABC World News Feed
RSS Data retrieved from https:--abcnews.go.com-abcnews-headlines
05-24 18:48 Truckers' strike leads to fuel shortages in Brazil
05-24 18:48 The marathon atop the world's deepest lake

删除char“,”并使用函数json_decode,然后享受