[英]Filter JSON Output with PHP
我已經在這個問題上撓頭好幾個小時了,但我似乎無法讓它發揮作用。 我有一個像這個例子的 JSON 輸出:
{
"response": {
"dataInfo": {
"foundCount": 494,
"returnedCount": 4
},
"data": [
{
"fieldData": {
"Closed_Date": "10/03/2021",
"Start_Date": "10/03/2021"
},
"portalData": {},
"recordId": "152962",
"modId": "3"
},
{
"fieldData": {
"Closed_Date": "11/14/2021",
"Start_Date": "11/06/2021"
},
"portalData": {},
"recordId": "153228",
"modId": "22"
},
{
"fieldData": {
"Closed_Date": "11/07/2021",
"Start_Date": "11/06/2021"
},
"portalData": {},
"recordId": "153329",
"modId": "7"
},
{
"fieldData": {
"Closed_Date": "11/08/2021",
"Start_Date": "11/08/2021"
},
"portalData": {},
"recordId": "153513",
"modId": "3"
}
]
},
"messages": [
{
"code": "0",
"message": "OK"
}
]
}
我想通過 Start_Date 字段使用 PHP 過濾此輸出,並計算每個月創建的數量。 我已經使用 JSON 解碼將 JSON 的結果放入一個數組中。
$urls = $ref->multicurlRestApi($urllinkarray, $postfield, $headers);
$decode_open = json_decode($urls[0],true);
例如,它的輸出如下。
第 10 個月:1
第 11 個月:3
現在非常感謝任何幫助,以免我發瘋
我首先將所有月份存儲在一個鍵值數組中,其中鍵是月份和該月條目數量的值。
現在,遍歷所有條目( $decode_open["response"]["data"]
)並計算月份。 我只是將日期轉換為 UNIX 時間戳,然后使用 PHP date
函數返回以獲取月份。
然后你只需要將月份添加到你的數組中(如果它不存在)並計算它。
// Your code to get the data
$urls = $ref->multicurlRestApi($urllinkarray, $postfield, $headers);
$decode_open = json_decode($urls[0],true);
$months = []; // <- The array we store the final data in
$items = $decode_open["response"]["data"];
foreach($items as $item) {
$month = date("m", strtotime($item["fieldData"]["Start_Date"]));
if(!isset($months[$month])) $months[$month] = 0; // <- Add the month to the array if it doesn't exist
$months[$month]++; // <- Increase the value for that month
}
print_r($months);
輸出應如下所示:
Array
(
[10] => 1
[11] => 3
)
<?php
$jsonStr = <<<JSON
{
"response": {
"dataInfo": {
"foundCount": 494,
"returnedCount": 4
},
"data": [
{
"fieldData": {
"Closed_Date": "10/03/2021",
"Start_Date": "10/03/2021"
},
"portalData": {},
"recordId": "152962",
"modId": "3"
},
{
"fieldData": {
"Closed_Date": "11/14/2021",
"Start_Date": "11/06/2021"
},
"portalData": {},
"recordId": "153228",
"modId": "22"
},
{
"fieldData": {
"Closed_Date": "11/07/2021",
"Start_Date": "11/06/2021"
},
"portalData": {},
"recordId": "153329",
"modId": "7"
},
{
"fieldData": {
"Closed_Date": "11/08/2021",
"Start_Date": "11/08/2021"
},
"portalData": {},
"recordId": "153513",
"modId": "3"
}
]
},
"messages": [
{
"code": "0",
"message": "OK"
}
]
}
JSON;
$response = json_decode($jsonStr, true);
if (JSON_ERROR_NONE !== json_last_error()) {
return;
}
$counter = [];
foreach ($response['response']['data'] as $item) {
$startDate = new DateTime($item['fieldData']['Start_Date']);
$month = $startDate->format('m');
if (key_exists($month, $counter)) {
$counter[$month] += 1;
} else {
$counter[$month] = 1;
}
}
var_dump($counter);die;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.