douxian7117 2017-11-09 16:11
浏览 31
已采纳

从多维数组中取消设置变量特定键

I have different multidimensional arrays with different keys and values:

$array_1 = array('cars' => array('audi' => array('a3' => array('one', 'two', 'three'), 'a5' => array('five', 'six', 'seven')), 'mercedes' => array('type_1' => array('submodel' => array('whatever'))), 'other_cat' => array('different_things')));

then I would like to unset a specific key, for example:

unset($array_1['cars']['audi']['a5']);

Now I like to "split it up", to have the key variable.

$to_unset = ['cars']['audi']['a5']; 

How can I unset that specific (variable!) key?

Aäron

  • 写回答

3条回答 默认 最新

  • dpca4790 2017-11-09 16:49
    关注

    An easy utility to avoid removing array keys that do not exist by accident:

    function removeArrayKey($path, &$array ) {
    
        $array_temp = &$array;
        $previousItem = null;
    
        $path_bits = explode( ".", $path );
    
            foreach( $path_bits as &$path_bit ) {
    
               if( !isset( $array_temp[ $path_bit ] ) ) {
                      die("Error" . $path_bit);
                       //throw new Exception( "Path does not exist in array" );
                }
    
                $previousItem = &$array_temp;
                $array_temp = &$array_temp[ $path_bit ];
    
            }
    
            if( isset( $previousItem ) ) {
    
                 unset( $previousItem[ $path_bit ] );
    
            }
    
            return $array;
    
    }
    

    To use the function, simply use removeArrayKey( "cars.mercedes.cars", $array_1 ); and separate each array index with a .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画