我有3個目錄命名september,october并november在maindirectory 2021。在所有這 3 個目錄中都是 json 檔案,如下所示:
{
"id": "id_2021-09-05_2200",
"date": "2021-09-05",
"guests": 32 // total guests for that day
}
每個月,我都需要guests那個月的總和。(將當月所有 json 檔案中的所有訪客加在一起)。
到目前為止,我有這個代碼,但我每個月都在計算:
$monthdirs = array_filter(glob('data/2021/*'), 'is_dir'); // read all month-dirs in year 2021
foreach($monthdirs as $monthdir) {
$monthfiles = glob($monthdir.'/*.json'); // all json files in a specific month
}
foreach($monthfiles as $monthfile) {
$arr[] = json_decode(file_get_contents($monthfile),true); // php assoc array
foreach($arr as $key => $val) {
$tot_guests_monthes[] = $val['guests']; // new array from each month with the sum of guests from all the json files in that month
}
}
foreach($tot_guests_monthes as $tot_guests_month) {
echo $tot_guests_month.'<br />';
}
我認為在第二個 foreach 回圈中我做錯了什么。我的最終輸出應該是 3 個值,例如:
200 // all guests september
300 // all guests october
400 // all guests november
uj5u.com熱心網友回復:
$...[] =基本上是一個array_push,這意味著$tot_guests_monthes[] = $val['guests'];將針對中每個元素創建一個新元素$arr的每一個$monthfile,而不是求和。
總結一個月內的所有值,然后將它們添加到$tot_guests_monthes應該作業:
$tot_guests_monthes = [];
$monthdirs = array_filter(glob('data/2021/*'), 'is_dir'); // read all month-dirs in year 2021
foreach($monthdirs as $monthdir) {
$monthfiles = glob($monthdir.'/*.json'); // all json files in a specific month
$sum = 0;
foreach($monthfiles as $monthfile) {
$arr = json_decode(file_get_contents($monthfile), true);
$sum = $arr['guests'];
}
$tot_guests_monthes[] = $sum;
}
foreach($tot_guests_monthes as $tot_guests_month) {
echo $tot_guests_month.'<br />';
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366618.html
