我正在尝试使用PHP,我想知道是否有一种简单的方法可以实现这一目标:
我有2个阵列:
$array1 = ('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J')
$array2 =('$', '%', '&')
如何在array2中定义的分隔符之间获得4个单独的数组?换句话说,我应该得到4个数组:
('A', 'B')
('C', 'D', 'E')
('F', 'G', 'H', 'I')
('J')
答案 0 :(得分:3)
这个怎么样?
<?php
/**
* @author - Sephedo
* @for - ImTryinl @ Stackoverflow
* @question - http://stackoverflow.com/questions/18705886/splitting-an-array-based-on-delimiters-from-another-array
*/
$array1 = array('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J');
$array2 = array('$', '%', '&');
$return = array();
$x = 0;
foreach( $array1 as $value )
{
if( in_array( $value, $array2 ) )
{
$x++;
}
else
{
$return[$x][] = $value;
}
}
var_dump( $return );
?>
经过测试,返回
array
0 =>
array
0 => string 'A' (length=1)
1 => string 'B' (length=1)
1 =>
array
0 => string 'C' (length=1)
1 => string 'D' (length=1)
2 => string 'E' (length=1)
2 =>
array
0 => string 'F' (length=1)
1 => string 'G' (length=1)
2 => string 'H' (length=1)
3 => string 'I' (length=1)
3 =>
array
0 => string 'J' (length=1)
答案 1 :(得分:1)
$array1 = array('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J');
$array2 = array('$', '%', '&');
$result = array_map(
'str_split',
preg_split(
'/[' . preg_quote(implode('', $array2)) . ']/',
implode('', $array1)
)
);
var_dump($result);
答案 2 :(得分:0)
这应该有效:
function splitArrays($source, $delimiters) {
$result = array();
$result[] = array();
$resultIndex = 0;
foreach($source as $value) {
if(in_array($value, $delimiters)) {
$result[] = array();
$resultIndex++;
}
else {
$result[$resultIndex][] = $value;
}
}
}
答案 3 :(得分:0)
在这里回答:http://codepad.org/dieF4Mbe
$array1 = array('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J');
$array2 = array('$', '%', '&');
$final_arrays = array();
$curr_array = 0;
foreach ($array1 as $char) {
if (!in_array($char, $array2)) {
$final_arrays[$curr_array][] = $char;
} else {
$curr_array++;
}
}
print_r($final_arrays);
答案 4 :(得分:0)
$array1 = array('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J');
$array2 =array('$', '%', '&');
$results = array();
$start = 0;
foreach($array2 as $key => $val){
$results[] = array_slice($array1, $start, array_search($val, $array1)-$start);
$start = array_search($val, $array1)+1;
}
print_r($results);
输出:
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => Array
(
[0] => C
[1] => D
[2] => E
)
[2] => Array
(
[0] => F
[1] => G
[2] => H
[3] => I
)
)