2014-09-10 53 views
1

我有一个数组,其中有另一个数组。我需要取消设置子数组的索引。取消设置另一个数组内的数组索引

array 
    0 => 
    array 
     'country_id' => string '1' (length=1) 
     'description' => string 'test' (length=4) 
    1 => 
    array 
     'country_id' => string '2' (length=1) 
     'description' => string 'sel' (length=5) 
    2 => 
    array 
     'country_id' => string '3' (length=1) 
     'description' => string 'soul' (length=5) 

现在我需要取消设置主数组的所有三个索引中的country_id。我使用的PHP和我最初认为未设置会做,直到我意识到我的数组嵌套。

我该怎么做?

+0

'的foreach($阵列作为&$ element){unset($ element ['country_id'];}' – Steve 2014-09-10 12:33:21

+0

'foreach($ array as&$ sub)unset($ sub ['country_id']);' – 2014-09-10 12:33:24

+0

[PHP - unset in一个多维数组](http:// stackoverflow的.com /问题/ 7260468/PHP-未设定功能于一个-多维阵列) – Joanvo 2014-09-10 12:52:49

回答

0
foreach ($original_array as &$element) { 
    unset($element['country_id']); 
} 

为什么&$element

因为foreach (...)将执行复制,所以我们需要将引用传递到“当前”元素,以取消它(而不是他的复印件)

0
foreach ($masterArray as &$subArray) 
    unset($subArray['country_id']); 

的想法是,你把每个子通过引用排列数组,并在其中取消设置键。


编辑:另一个想法,只是为了使事情有趣,将使用array_walk函数。

array_walk($masterArray, function (&$item) { unset ($item['country_id']); }); 

我不确定它是否更具可读性,并且函数调用会使它变慢。尽管如此,选择还是有的。

0
foreach($yourArray as &$arr) 
{ 
    unset($arr['country_id']); 
} 
0

您需要使用:

foreach ($array as &$item) { 
    unset($item['country_id']); 
} 

但循环后,你真的应该取消设置基准,否则你可能会遇到麻烦,因此正确的代码是:

foreach ($array as &$item) { 
    unset($item['country_id']); 
} 
unset($item); 
相关问题