如何在PHP的以下场景中将数组元素从关联数组中移除一个?

时间:2014-07-16 08:04:16

标签: php arrays associative-array array-key

我按照以下关联数组$_POST进行了跟踪:

Array
(
    [op] => add
    [product_id] => 12
    [pack] => Array
        (
            [1] => 1
        )
    [applicable_states] => Array
        (
            [0] => multiselect-all
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
            [5] => 5
            [6] => 6
            [7] => 7
            [8] => 8
            [9] => 9
            [10] => 10            
        )

    [total_count] => 3000
)

现在,您可以观察数组$_POST['applicable_states']中的第一个键[0] => multiselect-all。 我必须在操作数组之前检查此键。 每当此密钥存在于数组中时,我需要$_POST数组,如下所示:

Array
(
    [op] => add
    [product_id] => 12
    [pack] => Array
        (
            [1] => 1
        )
    [applicable_states] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
            [9] => 10            
        )

    [total_count] => 3000
)

现在,您可以从上面的数组中看到[0] => multiselect-all已从新结果数组中删除,并且每个数组值的位置都更改为1。我应该如何以最佳方式将$_POST数组转换为上面的结果数组?提前谢谢。

1 个答案:

答案 0 :(得分:3)

if (array_search('multiselect-all', $_POST['applicable_states']) === 0) 
    array_shift($_POST['applicable_states']);