【问题标题】:Have I written anything wrong in my code for array_shift function?我在 array_shift 函数的代码中写错了什么吗?
【发布时间】:2014-09-13 04:13:41
【问题描述】:

我的名为$data 的关联数组如下:

Array
(
    [op] => add
    [main_op] => 
    [rebate_id] => 
    [form_submitted] => yes
    [company_id] => 42
    [product_id] => 36
    [applicable_states] => Array
        (
            [0] => Array
                (
                    [state_id] => multiselect-all
                )

            [1] => Array
                (
                    [state_id] => 1
                )

            [2] => Array
                (
                    [state_id] => 2
                )

            [3] => Array
                (
                    [state_id] => 3
                )

            [4] => Array
                (
                    [state_id] => 4
                )

            [5] => Array
                (
                    [state_id] => 5
                )
       )
)

我想将数组 $data['applicable_states'] 向后移动一位。为此,我编写了以下代码,但它不起作用。你能帮我纠正我在代码中犯的错误吗?以下是我的代码。

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

预期的输出数组如下:

Array
(
    [op] => add
    [main_op] => 
    [rebate_id] => 
    [form_submitted] => yes
    [company_id] => 42
    [product_id] => 36
    [applicable_states] => Array
        (
            [0] => Array
                (
                    [state_id] => 1
                )

            [1] => Array
                (
                    [state_id] => 2
                )

            [2] => Array
                (
                    [state_id] => 3
                )

            [3] => Array
                (
                    [state_id] => 4
                )

            [4] => Array
                (
                    [state_id] => 5
                )
       )
)

【问题讨论】:

  • 请解释你的问题,不清楚你想要实现什么 - 也许显示你预期的输出数组
  • @user574632:我已经添加了所需的输出数组。
  • 我没有看到不同
  • @ins0: 看看数组 $data['applicable_states']。不一样。
  • array_shift($data['applicable_states']); 应该可以工作。 @ins0 他想删除数组applicable_states中的第一个元素。

标签: php arrays associative-array key-value


【解决方案1】:

就像您的答案和给定的数据一样,您可以简单地使用array_maparray_filter 来根据您的给定规格折腾元素。

$data['applicable_states'] = array_filter(array_map(function($v){
    return ($v['state_id'] != 'multiselect-all') ? $v : null;
}, $data['applicable_states']));

http://de3.php.net/manual/en/function.array-map.php

http://php.net/manual/en/function.array-filter.php

【讨论】:

    【解决方案2】:

    你的代码有一个问题——你有复杂的数组,所以它不起作用——array_search 找不到值(总是返回 false)

    作为解决方案,您应该简单地使用:

    if ($data['applicable_states'][0]['state_id'] == 'multiselect-all') {
        array_shift($data['applicable_states']);   
    }
    

    【讨论】:

    • -1: array_shift 返回移位后的值,而不是缩短的数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2020-05-16
    • 2019-08-27
    • 2016-11-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多