[英]PHP array for google chart; loop thru array and group by 2
(在圣诞大餐之间)我再次陷入数组和逻辑分组的循环中。 这是我得到的数组
$aTest = Array
(
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period5',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 2
),
Array
(
'date' => 2017-05-04,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period5',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period1',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
)
);
这次我喜欢按类别分组并按时期分组总分。 Y 轴是类别,X 轴是周期。 最后我需要这个作为谷歌图表
/*period, total indoor, total gym, 'total indoor', 'total gym'*/
array(
['Period1', 0,1,'0','1'],
['Period2', 3,0,'3','0'],
['Period3', 0, 0,'0','0'],
['Period4', 4,0,'4','0'],
['Period5', 1,1,'1','1']
)
我有这个 php 代码:
foreach ($aTest as $value) {
//echo $value['period'].' - '.$value['score'].'<br/>';
if (empty($output[$value]['period']))
$output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
if(empty($output[$value]['category']))
$output[$value['catgeory']] = ['Gym Class' => 0, 'Indoor room' =>0];
$output[$value['category']] += $value['score'];
}
ksort($output);
但这只是按类别而不是按时间段来计算总分。 我想我也需要遍历周期,但是如何?
if (empty($output[$value]['period'])) $output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
$value是一个数组,您尝试检查$output[$value]
我看到您没有任何行总和周期值。
我有你的数据的解决方案。 我的代码是做什么的??
按类别分类的时期总分
$temp = []; $output = []; foreach($aTest as $value){ $period = $value['period']; $category = $value['category']; // Create default values if (empty($temp[$period])){ $temp[$period] = []; } if(empty($temp[$period][$category])){ $temp[$period][$category] = 0; } //Sum score $temp[$period][$category] += $value['score']; } //After Forech we have an array with ['period name' => ['category name' => score]]; //Sort values of the category change it if you want, you can add more option such as (item type for add '' to values) $arraySort = [ "Indoor room", //total indoor, "Gym Class", // total gym, "Indoor room", //'total indoor', "Gym Class" //'total gym' ]; foreach($temp as $period => $catsScore){ $periodItem = [$period]; foreach($arraySort as $cat){ $periodItem[] = $catsScore; } $output[] = $periodItem; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.