我在PHP中具有以下多维数组。
对于每个array(),本示例都有3条信息。 IRL,我有20多名。
Array
(
[0] => Array
(
[date] => 2019-04-23
[room] => 101
[rate] => 10
)
[1] => Array
(
[date] => 2019-04-25
[room] => 101
[rate] => 10
)
[2] => Array
(
[date] => 2019-04-26
[room] => 101
[rate] => 10
)
[3] => Array
(
[date] => 2019-04-25
[room] => 102
[rate] => 12
)
[4] => Array
(
[date] => 2019-04-26
[room] => 102
[rate] => 12
)
)
仅当room
和rate
相似时,才可以对来自该数组的数据进行分组吗?
例如,上一个数组的期望输出如下:
Array
(
[0] => Array
(
[room] => 101,
[rate] => 10,
[dates] => Array
(
[0] => 2019-04-23,
[1] => 2019-04-25,
[2] => 2019-04-26
)
)
[2] => Array
(
[room] => 102,
[rate] => 12,
[dates] => Array
(
[0] => 2019-04-25,
[1] => 2019-04-26
)
)
)
答案 0 :(得分:1)
您可以使用Array.reduce
代码
<?php
$res = array_reduce($you_array,function($acc,$val){
$room = array_search($val['room'],array_column($acc,'room'));
$rate = array_search($val['rate'],array_column($acc,'rate'));
if($rate == $room && $room > -1){
array_push($acc[$room]['date'],$val['date']);
}else{
$new_arr=$val;
$new_arr['date']=[$val['date']];
array_push($acc,$new_arr);
}
return $acc;
},[]);
print_r($res);
?>