Reputation: 1312
I'm experimenting with PHP and I was wondering if there is a simple way to accomplish this:
I have 2 arrays:
$array1 = ('A', 'B', '$', 'C', 'D', 'E', '%', 'F', 'G', 'H', 'I', '&', 'J')
$array2 =('$', '%', '&')
How can I get 4 separate arrays that are between the delimiters defined in array2? In other words, I should get 4 arrays:
('A', 'B')
('C', 'D', 'E')
('F', 'G', 'H', 'I')
('J')
Upvotes: 0
Views: 91
Reputation: 212412
$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);
Upvotes: 1
Reputation:
$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);
Output:
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
)
)
Upvotes: 0
Reputation: 8579
answer here: 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);
Upvotes: 0
Reputation: 3877
This should work:
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;
}
}
}
Upvotes: 0
Reputation:
How about this?
<?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 );
?>
Tested and this returns
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)
Upvotes: 3