我想通过在每个日期值处打破一个数组来创建一个多数组:
array(
'3/20/13', // date (start a new child array)
'14',
'dog',
'red',
'10/21/13', // date (start a new child array)
'3',
'cat'
)
我编写了一个复杂的foreach
函数,它通过检测值是否为日期来构建一个新数组:
$date = DateTime::createFromFormat('n/d/y', $value);
我想知道是否有更简单的方法来拆分数组,还是我必须单独检查每个值?我担心array_chunk
适用于某个时间间隔,但没有任何变体。如果PHP无法回调,我会感到非常惊讶。
我知道有一个类似的问题,但答案是手动循环每个值。(Breaking an array into groups based on values)。
答案 0 :(得分:1)
[]比你的foreach循环简单吗? :)
// Source array to break into child arrays based on regular expression delimiter
$array = array(
'3/20/13', // date (start a new child array)
'14',
'dog',
'red',
'10/21/13', // date (start a new child array)
'3',
'cat',
'01/02/03', // another example
'4',
'badger'
);
// Regular expression to break array into child arrays
$delimiter = '/\//';
// Finds index position of matching delimiter in array (e.g. 0, 4)
$childIndex = array_keys(preg_grep($delimiter, $array));
// For each matching delimiter get the beginning index position and length of entries before next child begins - they part that array_chunk doesn't support. We feed these begin/length into array_slice next to make our own array
for ($i=0; $i<count($childIndex); $i++):
$chunks[$i]['begin'] = $childIndex[$i];
// Last chunk doesn't need a length
if (isset($childIndex[$i+1])):
$chunks[$i]['len'] = $childIndex[$i+1]-$childIndex[$i];
endif;
endfor;
// For each begin/length chunk splice the source array into a child array
foreach ($chunks as $chunk):
if (isset($chunk['len'])):
$final[] = array_slice($array, $chunk['begin'], $chunk['len']);
else:
$final[] = array_slice($array, $chunk['begin']);
endif;
endforeach;
// Our new nested array
var_dump($final);
<强>结果
// Source
array (size=10)
0 => string '3/20/13' (length=7)
1 => string '14' (length=2)
2 => string 'dog' (length=3)
3 => string 'red' (length=3)
4 => string '10/21/13' (length=8)
5 => string '3' (length=1)
6 => string 'cat' (length=3)
7 => string '01/02/03' (length=8)
8 => string '4' (length=1)
9 => string 'badger' (length=6)
// Found delimiter positions
array (size=3)
0 => int 0
1 => int 4
2 => int 7
// Chunks
array (size=2)
'begin' => int 0
'len' => int 4
array (size=2)
'begin' => int 4
'len' => int 3
array (size=1)
'begin' => int 7
// Final nested array
array (size=3)
0 =>
array (size=4)
0 => string '3/20/13' (length=7)
1 => string '14' (length=2)
2 => string 'dog' (length=3)
3 => string 'red' (length=3)
1 =>
array (size=3)
0 => string '10/21/13' (length=8)
1 => string '3' (length=1)
2 => string 'cat' (length=3)
2 =>
array (size=3)
0 => string '01/02/03' (length=8)
1 => string '4' (length=1)
2 => string 'badger' (length=6)