【问题标题】:Unset index of an array inside another array未设置另一个数组中的数组索引
【发布时间】:2014-11-04 02:38:48
【问题描述】:

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

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,我最初认为 unset 会做,直到我意识到我的数组是嵌套的。

我该怎么做?

【问题讨论】:

标签: php json


【解决方案1】:
foreach ($original_array as &$element) {
  unset($element['country_id']);
}

为什么是&$element

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

【讨论】:

    【解决方案2】:
    foreach ($masterArray as &$subArray)
        unset($subArray['country_id']);
    

    这个想法是通过引用获取每个子数组并取消设置其中的键。


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

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

    我不确定它是否更具可读性,并且函数调用会使其变慢。不过,选择仍然存在。

    【讨论】:

      【解决方案3】:
      foreach($yourArray as &$arr)
      {
         unset($arr['country_id']);
      }
      

      【讨论】:

        【解决方案4】:

        你需要使用:

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

        但是在循环之后你真的应该取消设置引用,否则你可能会遇到麻烦,所以正确的代码是:

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

        【讨论】:

          猜你喜欢
          • 2013-12-27
          • 1970-01-01
          • 2023-01-13
          • 2016-03-09
          • 2021-12-08
          • 1970-01-01
          • 2020-06-11
          相关资源
          最近更新 更多