我已经在这个问题上挠了几个小时的头了,我似乎就是不能让它起作用。我有一个类似以下示例的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"
}
]
}我想使用PHP通过Start_Date字段过滤这个输出,并计算每个月创建了多少个。我使用JSON Decode将JSON的结果放入一个数组中。
$urls = $ref->multicurlRestApi($urllinkarray, $postfield, $headers);
$decode_open = json_decode($urls[0],true);例如,它的输出将如下所示。
10个月:1
月11: 3
我现在非常感谢任何帮助,以免我发疯。
发布于 2021-11-11 07:30:10
我首先将所有月份存储在一个key- value -array中,其中key是月份,value是该月的条目数量。
现在,遍历所有条目($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
)发布于 2021-11-11 07:42:34
<?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;https://stackoverflow.com/questions/69924452
复制相似问题