我的关联数组$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
)
)
)
答案 0 :(得分:0)
您的代码存在一个问题 - 您拥有复杂的数组,因此无法工作 - array_search
无法找到该值(将始终返回false)
作为解决方案,您应该简单使用:
if ($data['applicable_states'][0]['state_id'] == 'multiselect-all') {
array_shift($data['applicable_states']);
}
答案 1 :(得分:0)
就像您的答案和给定的数据一样,您可以简单地array_map
和array_filter
使用您指定的规格折腾元素。
$data['applicable_states'] = array_filter(array_map(function($v){
return ($v['state_id'] != 'multiselect-all') ? $v : null;
}, $data['applicable_states']));