没有一个就绪函数。但是您可以使用 array_filter 来查找起点所在的数组键。接下来用拼接将其分块。
<?php
$array1 = array(
0 => 'BMC305',
1 => '14:15',
2 => 'OneData',
3 => 'SecondData',
4 => ' ',
5 => 'BMC305',
6 => '14:15',
7 => 'OnlyData',
8 => ' ');
function findStartElement($var) {
return strpos($var, 'BMC') === 0;
}
$startElements = array_filter($array1, 'findStartElement');
$chunks = array();
$previousKey = null;
foreach ($startElements as $key => $value) {
if ($previousKey !== null) {
$chunks[] = array_splice($array1, $previousKey, $key - $previousKey);
}
$previousKey = $key;
}
// get remaining part.
$chunks[] = $array1;
var_dump($chunks);
?>
此外,如果你使用 PHP 5.3,你可以在这里用闭包做一些真正整洁的事情。
<?php
function chunkByValue($array, $value) {
$startElements = array_filter($array, function ($var) use ($value) {
return strpos($var, $value) === 0;
});
$chunks = array();
$previousKey = null;
foreach ($startElements as $key => $value) {
if ($previousKey !== null) {
$chunks[] = array_splice($array, $previousKey, $key - $previousKey);
}
$previousKey = $key;
}
// get remaining part.
$chunks[] = $array;
return $chunks;
}
$array1 = array(
0 => 'BMC305',
1 => '14:15',
2 => 'OneData',
3 => 'SecondData',
4 => ' ',
5 => 'BMC305',
6 => '14:15',
7 => 'OnlyData',
8 => ' ');
var_dump(chunkByValue($array1, 'BMC'));
?>