douziqian2871
2014-10-30 19:36
浏览 199
已采纳

以递归方式从多维数组中删除特定键

I am trying to create a function to remove keys from a dynamic multidimensional array, i need to give:

removeByIndex(['hello', 'my', 'world']);

And then the function needs to do this:

unset($array['hello']['my']['world']);

The number of indexes are dynamic, example:

removeByIndex(['hello', 'my']); // Do: unset($array['hello']['my']);
removeByIndex(['hello']); // Do: unset($array['hello']);

I tried to use some foreach loops, but i didn't find a solution yet.

Any help will be welcome.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建一个从动态多维数组中删除键的函数,我需要给出:

  removeByIndex(['hello','my','world']); 
   
 
 

然后功能需要 要做到这一点:

  unset($ array ['hello'] ['my'] ['world']); 
   \  n 
 

索引的数量是动态的,例如:

  removeByIndex(['hello','my']);  // Do:unset($ array ['hello'] ['my']); 
removeByIndex(['hello']);  // Do:unset($ array ['hello']); 
   
 
 

我试图使用一些 foreach 循环,但我没有 找不到解决方案了。

欢迎任何帮助。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongluojiao6322 2014-10-30 20:11
    已采纳

    No need for eval() with a little bit of referencing.

    /**
     * Remove index from multi-dimensional array.
     *
     * @param array $array
     *   The array to remove the index from.
     * @param array $indices
     *   Indexed array containing the indices chain up to the index that should be
     *   removed.
     * @return
     *   The array with the index removed.
     * @throws \InvalidArgumentException
     *   If the index does not exist within the array.
     */
    function removeByIndex(array $array, array $indices) {
      // Create a reference to the original array.
      $a =& $array;
    
      // Count all passed indices, remove one because arrays are zero based.
      $c = count($indices) - 1;
    
      // Iterate over all passed indices.
      for ($i = 0; $i <= $c; ++$i) {
        // Make sure the index to go down for deletion actually exists.
        if (array_key_exists($indices[$i], $a)) {
          // This is the target if we reached the last index that was passed.
          if ($i === $c) {
            unset($a[$indices[$i]]);
          }
          // Make sure we have an array to go further down.
          elseif (is_array($a[$indices[$i]])) {
            $a =& $a[$indices[$i]];
          }
          // Index does not exist since there is no array to go down any further.
          else {
            throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
          }
        }
        // Index does not exist, error.
        else {
          throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
        }
      }
    
      return $array;
    }
    
    print_r(removeByIndex(
      [ "test1" => [ "test2" => [ "test3" => "test" ] ], "test4" => "test" ],
      [ "test1", "test2", "test3" ]
    ));
    

    Since I mentioned it in the comments, one could (micro-)optimize the function, but I advice against it, since it is less readable and might confuse some programmers.

    <?php
    
    function removeByIndex(array $array, array $indices) {
      $a =& $array;
      $c = count($indices) - 1;
      $i = 0;
      do {
        if (array_key_exists($indices[$i], $a)) {
          if ($i === $c) {
            unset($a[$indices[$i]]);
            return $array;
          }
          elseif (is_array($a[$indices[$i]])) {
            $a =& $a[$indices[$i]];
          }
          else break;
        }
        else break;
      }
      while (++$i);
      throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题