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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)