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

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

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.

  • 写回答

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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?