从Laravel PHP中的API返回消息中解析一个值

时间:2015-07-04 02:06:10

标签: php api laravel

我有一个API,我正在检索统计数据,需要解析某些信息以便在视图中返回。

我已经写了一个卷曲请求,以便从API中获取所需的信息。

// create curl resource 
        $ch = curl_init($cdnifybandwidthurl); 

    // sets GET 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); // -X      

    // $output contains the output string 
    $bandwidth_usage = curl_exec($ch); 

    // close curl resource to free up system resources 
    curl_close($ch);

此请求返回类似

的字符串
{"resource":"xxxx","datefrom":"2015-07-01",
"dateto":"2015-07-31","origin":"xxx.s3-website-us-east-1.amazonaws.com",
"overall_usage":[[{"timestamp":"2015-07-02 
00:00:00","cached":1739969,"non_cached":340826,"hits":76}]]}

我需要做的是在视图中返回non_cached数量。我无法从字符串中提取该数量。

1 个答案:

答案 0 :(得分:0)

总体使用情况看起来像是一个列表清单,我必须决定是否有更多项目,你想要哪一个。

您的API会返回JSON,因此我建议$obj = json_decode($bandwidth_usage, true)并在此处$obj['overall_usage']的列表中访问您需要的内容,或者我错过了这一点?

假设我已经走上正轨,你可以在这个特殊情况下继续:

$obj['overall_usage'][0][0]["non_cached"]
                      ^ first item of first array
                         ^ first item of second array
                            ^ item with key "non_cached"