如何在 php foreach 循环中从 json obj 获取值
Posted
技术标签:
【中文标题】如何在 php foreach 循环中从 json obj 获取值【英文标题】:how to get values from json obj in php foreach loop 【发布时间】:2022-01-13 15:34:02 【问题描述】:我有几个 json 文件,每个 json 文件如下所示:
"id": "id_1638974137049",
"weeknr": 48,
"dayhours": 5,
"tvt": 1.25
另一个文件:
"id": "id_1638974137050",
"weeknr": 48,
"dayhours": 6,
"tvt": 1.50
还有一个:
"id": "id_1638974137023",
"weeknr": 48,
"dayhours": 7,
"tvt": 1.75
现在我想制作一个表格作为输出,其中包含该周的 weeknr、dayhours 和 tvthours。这是我到目前为止所拥有的:
$files = glob('data/*.json'); // all json files in array
foreach($files as $file)
$objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array
foreach($objs as $key => $val)
$weeknr = $val['weeknr']; // weeknr
$array_dayhours[$weeknr] += $val['dayhours']; // sum of all the dayhours from that week
$array_tvthours[$weeknr] += $val['tvt']; // sum of all the tvt hours from that week
// i dont know how to handle this further to create a new array which contains per week the dayhours and tvt hours
我需要这样的输出(在表格中):
weeknr tot dayhours tot tvt hours
48 18 4.5
49 20 6.5
50 24 5.5
【问题讨论】:
嗯,问题是:我如何构建一个新的 foreach 来提供我想要实现的输出。$array_dayhours
包含 weeknr 和 dayhours 但我还需要绑定到该周的 tvt 小时
请分享var_export($objs);
的(样本),谢谢
【参考方案1】:
你可以这样做
$files = glob('data/*.json'); // all json files in array
$objs = [];
//array to store all data
$weeksData = [];
foreach($files as $file)
$objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array
foreach($objs as $key => $val)
//using weeknr as array key and pushing it to weekData array
$weeksData[$val['weeknr']] = [
'dayhours' => ($weeksData[$val['weeknr']]['dayhours'] ?? 0) + $val['dayhours'],
'tvt' => ($weeksData[$val['weeknr']]['tvt'] ?? 0) + $val['tvt']
];
【讨论】:
正是我要找的地方! TNhx【参考方案2】:<?php
$files = glob('data*.txt'); // all json files in array
foreach($files as $file)
$objs[] = json_decode(file_get_contents($file), true); // decode to php assoc array
$arrayResult=[];
foreach($objs as $key => $val)
$weeknr = $val['weeknr']; // weeknr
if(isset($arrayResult[$weeknr]) && is_array($arrayResult[$weeknr])) // If already exist
$arrayResult[$weeknr]=["weeknr"=>$val['weeknr'],"dayhours"=>$arrayResult[$weeknr]["dayhours"]+$val['dayhours'], "tvt"=>$arrayResult[$weeknr]["tvt"]+$val['tvt']];
else // for new entry
$arrayResult[$weeknr]=["weeknr"=>$val['weeknr'],"dayhours"=>$val['dayhours'], "tvt"=>$val['tvt']];
您可以使用 $arrayResult 进行打印
【讨论】:
以上是关于如何在 php foreach 循环中从 json obj 获取值的主要内容,如果未能解决你的问题,请参考以下文章
在 PHP CodeIgniter foreach 循环中从数据库中提取和更新数据
使用 PHP for 和 foreach 循环从 JSON 数据中检索视频信息时遇到问题 - YouTube API 3