在Laravel PHP中解析API返回消息中的值


Parse a value from API return message in Laravel PHP

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

我写了一个curl请求,从提供的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}]]}

我需要做的是返回视图中的未缓存数量。我很难从字符串中提取出那个数量。

总体用法看起来像是一个列表列表,在我看来,如果有更多的项目,你必须决定要哪个。

您的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"