从数组中删除元素时,unset会留下空索引

时间:2013-09-11 22:31:51

标签: php

我在SO中的许多答案中发现'unset'从数组中删除了元素但是在运行此代码后我发现了截然不同的结果。 索引3和4不应该存在,但它们确实存在。

有人可以解释一下吗?

$offset_arr = array();
array_push($offset_arr, array('11','22','33','11','22','33','11','22','33','33','005'));
array_push($offset_arr, array('11','22','33','11','22','33','11','22','33','33','005'));
array_push($offset_arr, array('11','22','33','11','22','33','11','22','33','33','006'));
array_push($offset_arr, array('11','22','33','11','22','33','11','22','33','33','007'));
array_push($offset_arr, array('11','22','33','11','22','33','11','22','33','33','008'));

$temp_arr = make_offset_array_size_smaller($offset_arr);

echo "\n\nafter running a function array size=".count($temp_arr)."\n\n";
print_r($temp_arr);
print_r($temp_arr[4]); // I don't want this. It should work for [2] not [4]

function make_offset_array_size_smaller($input_arr){
    $result_arr = array();
    $lowest_value = '1000';
    foreach($input_arr as $row_arr) {
        if((int)($lowest_value) > (int)($row_arr[10])) {
            $lowest_value = $row_arr[10];
        }
    }

    $input2_arr = $input_arr;
    foreach($input2_arr as $elementKey => $element) {
        echo "\n --- ".$elementKey." - ".$element[10];
        if((int)($lowest_value) == (int)($element[10])) {
            unset($input2_arr[$elementKey]);
        }

    }
return $input2_arr;
}

结果

 --- 0 - 005
 --- 1 - 005
 --- 2 - 006
 --- 3 - 007
 --- 4 - 008

after running a function array size=3

Array
(
    [2] => Array
        (
            [0] => 11
            [1] => 22
            [2] => 33
            [3] => 11
            [4] => 22
            [5] => 33
            [6] => 11
            [7] => 22
            [8] => 33
            [9] => 33
            [10] => 006
        )

[3] => Array
    (
        [0] => 11
        [1] => 22
        [2] => 33
        [3] => 11
        [4] => 22
        [5] => 33
        [6] => 11
        [7] => 22
        [8] => 33
        [9] => 33
        [10] => 007
    )

[4] => Array
    (
        [0] => 11
        [1] => 22
        [2] => 33
        [3] => 11
        [4] => 22
        [5] => 33
        [6] => 11
        [7] => 22
        [8] => 33
        [9] => 33
        [10] => 008
    )

)
Array
(
    [0] => 11
    [1] => 22
    [2] => 33
    [3] => 11
    [4] => 22
    [5] => 33
    [6] => 11
    [7] => 22
    [8] => 33
    [9] => 33
    [10] => 008
)

0 个答案:

没有答案