开发者

php split array between two values

i have an array like:

Array ( [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 [7] => #!A1#DC [8] => #IMSR102.50/74.82 [9] => #HV40 [10] => #PR5/5/ [11] => #RX0 [12] => #ERN/1//1 [13] => #Q2 etc etc with hundreds o values

i get this array from a file (with the function file($filename) ) and i need to split it in many subarray.

"!A1#DC" this is the beginning of a series of values ​​that ends with #Q2 but the number of the values between the beginning and the end is not always the same and the only 2 values that are same are the two given ("!A1#DC" for the beginning and "#Q2" for the end) how can i get somethings like this?

Array ( 
[0] => Array (  [0] => #!A1#DC [1] => #IMSR102.71/74.82 [2] => #HV50开发者_开发问答 [3] => #PR7/7/ [4] => #RX0 [5] => #ERN/1//0 [6] => #Q2 ) 
    [1] => Array (
     [1] => #!A1#DC [2] => #IMSR102.50/74.82 [3] => #HV40 [4] => #PR5/5/ [5] => #RX0 [6] => #ERN/1//1 [7] => #Q2 etc etc

could you please help me?

thanks


Loop through an array. When you meet starting value, store it's index. When you meet ending value, use array_slice() to extract the part between the last pair of starting and ending values, store this part into another array.

$source = array (
    '#!A1#DC',
    '#IMSR102.71/74.82',
    '#HV50',
    '#PR7/7/',
    '#RX0',
    '#ERN/1//0',
    '#Q2',
    '#!A1#DC',
    '#IMSR102.50/74.82',
    '#HV40',
    '#PR5/5/',
    '#RX0',
    '#ERN/1//1',
    '#Q2',
);

$dest = array();

$startValue = '#!A1#DC';
$endValue = '#Q2';

$startIndex = 0;
foreach ( $source as $index => $value ) {
    if ( $value === $startValue ) {
        $startIndex = $index;
    } else
    if ( $value === $endValue ) {
        $dest[] = array_slice($source, $startIndex, $index - $startIndex + 1);
    }
}

print_r($dest);


Basically you need to loop through each element of $input, collecting those within START and END elements into a separate array:

$input = array("#!A1#DC", "A", "B", "#Q2");
$values = array();
$current = 0;

define("START", "#!A1#DC");
define("END", "#Q2");
for ($i = 0; $i < count($input); $i++) {
    if ($input[$i] == END) {
        // Ignore any elements after this point until we see START
        $current = null;
    } else if ($input[$i] == START) {
        // Create a new current collection array
        $current = count($values);
        $values[$current] = array();
    } else {
        // Store the value if we are collecting
        if ($current !== null) {
            $values[$current][] = $input[$i];
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜