开发者

splitting an array at a given line into two parts, inserting another line, and rejoining them

I have an array full of sub arrays. I need to break apart the first array at a given line number, and then insert a new line, and then combine them all back into their original structure.

This is what im working with now

$csvpre = explode("###", $data);

$i = 0;
$bgc = 0;

    foreach ( $csvpre AS $key => $value){
        $info = explode("%%", $value);
        $i++;
        if($i == "1"){
            echo "<tr bgcolor=#efefef><td></td>";
          开发者_JAVA百科      foreach ( $info as $key => $value ){ echo "<td>$value</td>"; }
            echo "</tr>";

        } else {

            if($bgc&1) { $bgcgo = "bgcolor=\"#b9b9b9\"" ;} else { $bgcgo = "bgcolor=\"#d6d6d6\""; }
            echo "<tr $bgcgo><td></td>";
            echo "<td><input type=button value=\"clone #$i\"></td>";
            $j = 0;
                foreach ( $info as $key => $value ){ 
                    $j++;

                        if($j != 8){
                            echo "<td>$value</td>";
                        }else{
                            echo "<td><textarea name=ddesc[]>$value</textarea></td>";
                        }
                }
            echo "</tr>";
            $bgc++;
        }       
    }

What i need to create, is a function that will take a value for $i, say 10, and at that line split the array into two pieces $arraya and $arrayb. Then i need to combine them back together while including a new line...

pseudo code

$startarray = array(Line0, Line1, Line2, Line3, Line4); $splitline = 2; $arraya = splitup($startarray, $splitline); $arrayb = splitdown($startarray, $splitline);

ArrayA would then consist of Line0, Line1, Line2. And ArrayB would consist of Line3, Line4. Then we run the magic function.

$newline = "Line2.5";
$newarray = somefunction($arraya, $newline, $arrayb);

And $newarray would then look like

Line0, Line1, Line2, Line2.5, Line3, Line4


If I understand your question correctly, array_splice() can do that all in one go:

$array = array('Line0', 'Line1', 'Line2', 'Line3', 'Line4');
array_splice($array, 3, 0, 'Line2.5');
print_r($array);

which outputs:

Array
(
    [0] => Line0
    [1] => Line1
    [2] => Line2
    [3] => Line2.5
    [4] => Line3
    [5] => Line4
)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜