我真的需要一些帮助来解决这个问题。
我有很多数组,我想合并其中一些。如下所示。
while ($row = $db->fetch_array($result_set)) {
$year = $row['year(Tidspunkt)'];
$month_num = $row['month(Tidspunkt)'];
$month = $cal->name_of_month($row['month(Tidspunkt)']);
$type = $row['Klubtype'];
$visits = $row['count(Handling)'];
$days_in_month = $cal->days_in_month($month_num,$year);
$avg = $visits / $days_in_month;
$object_array[]= array('month' => $month , 'visits' => $visits, 'type' => $type, 'avg' => $avg);
}
return $month_array;
输出看起来像这样
Array (
[0] => Array ( [month] => Januar [visits] => 891 [type] => FK [avg] => 28.7419354839 )
[1] => Array ( [month] => Januar [visits] => 23 [type] => UK [avg] => 0.741935483871 )
)
现在我想根据月份的值合并这两个数组。想象一下当我有一整年的阵列时。那么最好有 12 个数组而不是 24 个。
谢谢你帮助我。
我想这可能就是你想要的......
$newArray = array();
foreach($array as $value) {
$month = $value['month'];
unset($value['month']);
$newArray[$month][] = $value;
}
这会给你一些类似...
Array (
['Januar'] => Array (
[0] => Array( [visits] => 891 [type] => FK [avg] => 28.7419354839 )
[1] => Array ( [visits] => 23 [type] => UK [avg] => 0.741935483871 )
)
我建议使用 GROUP BY 和聚合函数在 SQL 层中执行所有计算。
迭代结果集时,将每个唯一月份的引用变量推入结果数组中。然后,您只需将行数据推送为由月份值标识的引用的新子级。
$danishMonths = [
1 => 'Januar',
2 => 'Februar',
3 => 'Marts',
4 => 'April',
5 => 'Maj',
6 => 'Juni',
7 => 'Juli',
8 => 'August',
9 => 'September',
10 => 'Oktober',
11 => 'November',
12 => 'December'
];
$sql = <<<SQL
SELECT
YEAR(Tidspunkt) year,
MONTH(Tidspunkt) month_num,
Klubtype type,
COUNT(Handling) visits,
COUNT(Handling) / DAY(LAST_DAY(MIN(Tidspunkt))) avg_visits
FROM visits
WHERE YEAR(Tidspunkt) = '2024'
GROUP BY year, month_num, type
ORDER BY year, month_num, type
SQL;
$month_array = [];
foreach ($mysqli->query($sql) as $row) {
if (!isset($ref[$row['month_num']])) {
$month_array[] =& $ref[$row['month_num']];
}
$ref[$row['month_num']][] = [
'month' => $danishMonths[$row['month_num']],
'visits' => $row['visits'],
'type' => $row['type'],
'avg' => $row['avg_visits']
];
}
var_export($month_array);
使用我的假样本数据,这是输出的结构:
array (
0 =>
array (
0 =>
array (
'month' => 'Januar',
'visits' => '3',
'type' => 'FK',
'avg' => '0.0968',
),
1 =>
array (
'month' => 'Januar',
'visits' => '2',
'type' => 'UK',
'avg' => '0.0645',
),
),
1 =>
array (
0 =>
array (
'month' => 'Februar',
'visits' => '2',
'type' => 'FK',
'avg' => '0.0690',
),
1 =>
array (
'month' => 'Februar',
'visits' => '1',
'type' => 'UK',
'avg' => '0.0345',
),
),
)