我正在尝试合并具有相同日期值的子数组
我在使用in_array()或array_merge()方面并没有取得多少成功。
我的代码是这样的:
$lectureTimes = array (
0 =>
array (
'CDate' => '2019-03-02',
'a1' => '07:45',
'a2' => '08:00',
),
1 =>
array (
'CDate' => '2019-03-06',
'b1' => '05:00',
'b2' => '05:15',
),
2 =>
array (
'CDate' => '2019-03-18',
'c2' => '05:15',
'c1' => '05:30',
),
3 =>
array (
'CDate' => '2019-03-18',
'd1' => '04:45',
'd2' => '05:00',
),
)
这是我想要获得的输出:
$lectureTimes = array (
0 =>
array (
'CDate' => '2019-03-02',
'a1' => '07:45',
'a2' => '08:00',
),
1 =>
array (
'CDate' => '2019-03-06',
'b1' => '05:00',
'b2' => '05:15',
),
2 =>
array (
'CDate' => '2019-03-18',
'c2' => '05:15',
'c1' => '05:30',
'd1' => '04:45',
'd2' => '05:00',
),
)
为每个CDate创建一个新的HTML表行。
最终,我在客户端使用了JS来合并重复的行,但是我希望使用完整的PHP解决方案。
答案 0 :(得分:2)
由于“ CDate”值与这些值处于同一级别,因此无法用一种方法合并这些值。您应该遍历值以合并它们。可以使用类似这样的东西:
$mergedLectureTimes = array();
foreach ($lectureTimes as $lectureTimeSet) {
if(!isset($mergedLectureTimes[$lectureTimeSet['CDate']])) {
$mergedLectureTimes[$lectureTimeSet['CDate']] = array();
}
$mergedLectureTimes[$lectureTimeSet['CDate']] = array_merge($mergedLectureTimes[$lectureTimeSet['CDate']], $lectureTimeSet);
}
var_dump($mergedLectureTimes);
结果:
array(3) {
["2019-03-02"]=>
array(3) {
["CDate"]=>
string(10) "2019-03-02"
["a1"]=>
string(5) "07:45"
["a2"]=>
string(5) "08:00"
}
["2019-03-06"]=>
array(3) {
["CDate"]=>
string(10) "2019-03-06"
["b1"]=>
string(5) "05:00"
["b2"]=>
string(5) "05:15"
}
["2019-03-18"]=>
array(5) {
["CDate"]=>
string(10) "2019-03-18"
["c2"]=>
string(5) "05:15"
["c1"]=>
string(5) "05:30"
["d1"]=>
string(5) "04:45"
["d2"]=>
string(5) "05:00"
}
}