我有一个如下数组:
Array
(
[0] => Array
(
[record_id] => 3
[task_date] => 2018-10-02
)
[1] => Array
(
[record_id] => 5
[task_date] => 2018-10-02
)
[2] => Array
(
[record_id] => 1
[task_date] => 2018-09-27
)
)
我希望它采用以下格式:
Array
(
[0] => Array
(
[0] => Array
(
[record_id] => 3
[task_date] => 2018-10-02
)
[1] => Array
(
[record_id] => 5
[task_date] => 2018-10-02
)
)
[1] => Array
(
[0] => Array
(
[record_id] => 1
[task_date] => 2018-09-27
)
)
)
以便每个子数组包含相同日期的元素。
答案 0 :(得分:0)
这将从数据中收集唯一的日期,然后构建一个数组,将同一日期的软管项目分组:
$data = [
[
'record_id' => 3,
'task_date' => '2018-10-02'
],
[
'record_id' => 5,
'task_date' => '2018-10-02'
],
[
'record_id' => 1,
'task_date' => '2018-09-27'
]
];
$dates = [];
foreach ($data as $item) {
$dates[] = $item['task_date'];
}
$dates = array_unique($dates);
$out = [];
foreach ($dates as $date) {
$date_group = [];
foreach ($data as $item) {
if ($item['task_date'] == $date) {
$date_group[] = $item;
}
}
$out[] = $date_group;
}
var_dump($out);
答案 1 :(得分:0)
您可以这样做。
$inputArray = array("0"=>array('record_id'=>'3','task_date'=>'28-10-02'),'1'=>array('record_id'=>'3','task_date'=>'28-10-02'),'2'=>array('record_id'=>'3','task_date'=>'28-10-03'));
$outputArray = array();
foreach($inputArray as $key=>$value){
$outputArray[$value['task_date']][]=$value;
}
print_r(array_values($outputArray));
答案 2 :(得分:0)
根据@Barry的回答,解决方案可能如下所示:
<?php
$data = [
[
'record_id' => 3,
'task_date' => '2018-10-02'
],
[
'record_id' => 5,
'task_date' => '2018-10-02'
],
[
'record_id' => 1,
'task_date' => '2018-09-27'
]
];
$out = [];
$datesIterated = [];
foreach ($data as $date) {
if(in_array($date['task_date'], $datesIterated)) {
continue;
}
$out[] = array_values(array_filter($data, function($item) use ($date) {
if ($item['task_date'] == $date['task_date']) {
return $item;
}
}));
$datesIterated[] = $date['task_date'];
}
var_dump($out);
我们需要在array_filter的结果上调用array_values以再次实现顺序索引,有关更多信息,请参见this question。
答案 3 :(得分:0)
$common = [];
$output = [];
$i = 0;
foreach($input as $key=>$value){
if(in_array($value['task_date'],$common)){
$k = array_search($value['task_date'],$common);
$output[$k][$i] = $value;
}else{
$output[][] = $value;
}
$common[] = $value['task_date'];
$i++;
}
print_r($output);
我希望它对您有用。
答案 4 :(得分:0)
PHP中的所有数组都是关联的。
打高尔夫球吗?
。
$data = [
0 => [
"record_id" => 3,
"task_date" => "2018-10-02"
],
1 => [
"record_id" => 5,
"task_date" => "2018-10-02"
],
2 => [
"record_id" => 1,
"task_date" => "2018-09-27",
]
];
$out = [];
foreach($data as $task)
{
$out[$task["task_date"]][] = $task;
}
return array_values($out);