我正在尝试将一个PHP函数组合在一起,该函数获取活动数据并将其显示在图表中。我有这方面的工作,但我想做的是平均一个星期的活动数据,并平均每个点在一起。每天有480个数据点--每三分钟一次。每天都存储为Json数组,如下所示(缩短):
{"12:00 AM":5.8227539,"12:03 AM":0,"12:06 AM":0,"12:09 AM":2.44,}
{"12:00 AM":2.569,"12:03 AM":0.864,"12:06 AM":0,"12:09 AM":3.14,}
{"12:00 AM":0.0,"12:03 AM":4.2,"12:06 AM":4.632,"12:09 AM":2.11,}PHP中是否有一种方法可以将多个json数组平均在一起,并输出一个具有平均值的json字符串?谢谢。
编辑,因此上述3个数组的平均值将导致:
{"12:00 AM":2.7972,"12:03 AM":1.688,"12:06 AM":1.544,"12:09 AM":2.5633}发布于 2016-06-25 03:15:51
您可以使用json_decode将JSON数据转换为PHP。然后,如果将结果转换为关联数组,则可以利用PHP的array_sum和count函数计算平均值:
// load your json data into a PHP array
$data = (array) json_decode( $json );
// calculate average
$avg = array_sum($data) / count($data);这对于一个JSON对象就足够了。如果要对多个JSON对象执行平均值,则需要将它们全部加载到一起。最简单的方法是将它们编码到一个JSON对象数组中:
// format your json data into an array of objects
$json = '[
{"12:00 AM":5.8227539,"12:03 AM":0,"12:06 AM":0,"12:09 AM":2.44},
{"12:00 AM":2.569,"12:03 AM":0.864,"12:06 AM":0,"12:09 AM":3.14},
{"12:00 AM":0.0,"12:03 AM":4.2,"12:06 AM":4.632,"12:09 AM":2.11}
]';然后,您可以在遍历数组时执行平均值计算:
// load your json data into a PHP array
$data = json_decode( $json );
$count = 0; //let's track our count
$sum = 0; //and sum
// traverse the array, calculating the total sum by
// aggregating the sum of each inner object
foreach( $data as $obj ) {
$loc_array = (array) $obj; //cast to array
$count += count($loc_array); //add to count
$sum += array_sum($loc_array); //add to sum
}
$avg = $sum / $count; //calculate average最后一步是将计算格式化为JSON字符串:
$output = json_encode([ 'avg' => $avg ]);用时间点平均值更新
为了计算每个时间点的平均值,我们可以使用array_walk和一个辅助函数来聚合和计数。然后循环返回生成的数据,以计算平均值。
// load your json data into a PHP array
$data = json_decode( $json );
$a_helper = []; // track the sums and counts
$a_avgs = []; // we'll write the averages to this array
// We'll create a function we can use to write to our helper arrays
function generate_sums( $value, $key ) {
global $a_helper;
if( !isset($a_helper[$key]) ) {
$a_helper[$key] = [0,0]; // [sum,count]
}
$a_helper[$key][0] += $value; // add sum
$a_helper[$key][1] += 1; // add count
}
// Have array_walk populate the helper arrays using our function
foreach( $data as $obj ) {
$loc_array = (array) $obj; //cast to array
array_walk($loc_array, 'generate_sums');
}
// Loop over each value, calculating the averages
foreach( $a_helper as $key => $pair ) {
$a_avgs[$key] = $pair[0] / $pair[1];
}
$output = json_encode( $a_avgs );
// => {"12:00 AM":2.7972513,"12:03 AM":1.688,"12:06 AM":1.544,"12:09 AM":2.5633333333333}注意,助手函数引用的是全局变量($a_helper)。虽然使用全局变量并不理想,但array_walk似乎不允许在其$userdata参数内传递引用,因为现在禁止按引用进行运行时传递。其他的工作也是可能的,但有点异国情调:
https://stackoverflow.com/questions/38024308
复制相似问题