我正在尝试将输入转换为我需要向我们显示Google Chart的数组
我得到的输入数组,
$inputArray = [
['date' => '2016-12-10', 'code' => 'P'],
['date' => '2016-12-15', 'code' => 'P'],
['date' => '2017-02-10', 'code' => 'P'],
['date' => '2017-02-14', 'code' => 'P'],
['date' => '2017-03-10', 'code' => 'P'],
['date' => '2017-03-05', 'code' => 'U'],
['date' => '2017-03-11', 'code' => 'U'],
['date' => '2017-03-12', 'code' => 'P'],
['date' => '2017-04-07', 'code' => 'T'],
['date' => '2017-04-18', 'code' => 'P'],
['date' => '2017-04-19', 'code' => 'T'],
['date' => '2017-07-10', 'code' => 'P'],
];
现在我需要按年份和月份进行分组并将代码值相加(4个不同的值)。对于这些我使用像这样的循环
function readPerMonth($tmpArray) {
if (empty($tmpArray)) {
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
} else {
$output = [];
foreach ($tmpArray as $value) {
$year = date('Y', strtotime($value['date']));
$month = date('M', strtotime($value['date']));
if (empty($output[$year][$month]))
$output[$year][$month] = ['P' => 0, 'T' => 0, 'U' => 0, 'E' => 0];
// Check for incident intensity
$output[$year][$month][$value['code']] += 1;
}
}
ksort($output);
ksort($output[$year][$month]);
return $output;
}
这给了我以下输出,因此最后一个数组是另一个顺序???
Array
(
[2017] => Array
(
[Feb] => Array
(
[P] => 11
[T] => 0
[U] => 0
[E] => 0
)
[Mar] => Array
(
[P] => 20
[T] => 0
[U] => 0
[E] => 0
)
[Apr] => Array
(
[P] => 12
[T] => 0
[U] => 0
[E] => 0
)
[May] => Array
(
[P] => 21
[T] => 0
[U] => 0
[E] => 0
)
[Jun] => Array
(
[E] => 0
[P] => 7
[T] => 0
[U] => 1
)
)
)
我是一个输入数组,我需要在这个JS中转换以绘制堆积的Google图表
$output = [
['2016-dec', 2, 0, 0, 0,'2'],
['2017-feb', 2, 0, 0, 0, '2'],
['2017-mar', 2, 0, 2, 0,'4'],
['2017-apr', 1, 1, 0, 0,'2'],
['2017-may', 1, 0, 0, 0, '1'],
];
我的php函数看起来像这样
function phpToJS($inputPHP) {
$return = '';
foreach ($inputPHP as $year => $months) {
foreach ($months as $monthValue => $codeValues) {
$sum = 0;
$return .= "['" . $year . " - " . $monthValue . "', ";
foreach ($codeValues as $key => $code) {
if ($key == '') {
$return .= $code;
} else {
$return .= $code . ',';
}
$sum += $code;
}
$return .= ",'" . $sum . "'],";
}
}
return $return;
}
$tmpArr = readPerMonth($inputArray);
$output = phpToJS($tmpArr);
但是由于最后一个数组的顺序不正确,Google Chart显示错误。
ps:很抱歉打了发送而没有完成我的问题标题:/