Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在另一个数组中取消设置一个数组的索引_Php_Json - Fatal编程技术网

Php 在另一个数组中取消设置一个数组的索引

Php 在另一个数组中取消设置一个数组的索引,php,json,Php,Json,我有一个数组,其中有另一个数组。我需要取消设置子数组的索引 array 0 => array 'country_id' => string '1' (length=1) 'description' => string 'test' (length=4) 1 => array 'country_id' => string '2' (length=1) 'description' => s

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

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\u id
。我正在使用PHP,我最初认为unset可以,直到我意识到我的数组是嵌套的

我该怎么做

foreach ($original_array as &$element) {
  unset($element['country_id']);
}
为什么
和$element

因为
foreach(…)
将执行一个复制,所以我们需要将引用传递给“current”元素以取消设置它(而不是他的副本)

其思想是通过引用获取每个子数组,并在其中取消设置键


编辑:为了让事情变得有趣,另一个想法是使用
array\u walk
函数

array_walk($masterArray, function (&$item) { unset ($item['country_id']); });
我不确定它是否更可读,函数调用会使它变慢。不过,该选项仍然存在。

您需要使用:

foreach($yourArray as &$arr)
{
   unset($arr['country_id']);
}
foreach ($array as &$item) {
  unset($item['country_id']);
}
但是在循环之后,您应该真正取消设置引用,否则您可能会遇到麻烦,因此正确的代码是:

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