11

I have an array of the form

$array = array(1 => 'a',
               2 => 'b',
               3 => 'c',
               4 => 'd')

and I would like to create a 'hole' between 2 and 3, i.e. obtain the following array

$array = array(1 => 'a',
               2 => 'b',
               4 => 'c',
               5 => 'd')

What do you reckon to be the best way to do this?

4

6 回答 6

4

This should work:

function array_drill_hole($input, $start, $end) {
    array_splice($input, $start, $end - $start, null);
    return $input;
}
于 2013-11-08T14:51:42.227 回答
2
$array = array_combine(array_merge(range(1, 2), range(4, 5)), $array);
于 2013-11-08T14:48:55.910 回答
1
define("N", 3);

$i = count($array);
while ($i >= N) {
   $array[$i+1] = $array[$i];
   $i--;
}
unset ($array[ N ]);

or the equivalent for version

define("N", 3);

for($i=count($array) ; $i >= N ; $i--) {
   $array[$i+1] = $array[$i];
}
unset ($array[ N ]);
于 2013-11-08T14:46:04.970 回答
0

I want to join: http://codepad.org/9JDGHxhK

array_splice($array, 2, 0, "");

return array_filter($array);
于 2013-11-08T14:57:06.260 回答
0

Here is a tested complete solution:

function makeHole($index,$holeArr) {
            $returnArr = array();
            $increaseFlag = false;
            foreach ($holeArr as $ind => $val) {
                if ($ind == $index || $increaseFlag) {
                    $increaseFlag = true;
                    $returnArr[$ind+1] = $val;
                } else {
                    $returnArr[$ind] = $val;
                }
            }
            return $returnArr;
        }

        $array = array(1 => 'a',
            2 => 'b',
            3 => 'c',
            4 => 'd');
        $result = makeHole(3,$array);
        echo '<pre>';
        print_r($result);
        echo '</pre>';
于 2013-11-08T14:58:00.263 回答
0
$array = array(1 => 'a',
               2 => 'b',
               3 => 'c',
               4 => 'd');
array_splice($array, 2, 0, " ");
array_splice($array, 3, 0, " ");
unset($array[3]);
unset($array[2]);

var_dump($array);

Output:

array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [4]=> string(1) "c" [5]=> string(1) "d" } 
于 2013-11-08T15:01:28.230 回答