我有这个数组
array:15 [▼
0 => 0
1 => 0
2 => 0
3 => "2018-10-20"
4 => "2018-10-21"
5 => "2018-10-22"
6 => "2018-10-23"
7 => "2018-10-24"
8 => 0
9 => 0
10 => "2018-10-27"
11 => "2018-10-28"
12 => "2018-10-29"
13 => "2018-10-30"
14 => "2018-10-31"
]
,我想以某种方式将存在于零值之间的每一组值提取到一个单独的数组中。
我希望结果是类似的。
array:1 [▼
0 => "2018-10-20"
1 => "2018-10-21"
2 => "2018-10-22"
3 => "2018-10-23"
4 => "2018-10-24"
]
array:2 [▼
0 => "2018-10-27"
1 => "2018-10-28"
2 => "2018-10-29"
3 => "2018-10-30"
4 => "2018-10-31"
]
答案 0 :(得分:3)
您可以使用foreach循环执行此操作:
$chunks = [];
$current_chunk = [];
foreach ($arr as $item) {
if ($item == 0) {
if (count($current_chunk) > 0) {
$chunks[] = $current_chunk;
$current_chunk = [];
}
continue;
}
$current_chunk[] = $item;
}
if (count($current_chunk) > 0) {
$chunks[] = $current_chunk;
}
var_dump($chunks);
观看演示here。
答案 1 :(得分:0)
array_reduce($array, function ($prev, $curr) {
if (count($prev) == 0 && $curr == 0) {
return $prev;
}
if ($curr == 0) {
array_push($prev, []);
return $prev;
}
if (count($prev) == 0) {
return array(array($curr));
}
array_push($prev[count($prev) - 1], $curr);
return $prev;
}, []);