dtjo51649 2015-09-17 14:05
浏览 72
已采纳

PHP:如何使用另一个关联数组从一个关联数组中删除元素

I have two arrays one which has all the data, and another associative array of the keys I would like to remove.

$all_data = array(
    'one' =>array(
        'one_one'=>array(
            'one_one_one'=>'value',
            'one_one_two'=>'value',
        ),
        'one_two'=> array(
            'one_two_one'=>'value',
            'one_two_two'=>'value',
        )
    ),
    'two' =>array(
        'two_one'=>array(
            'two_one_one' =>'value',
            'two_one_two' =>'value',
        ),
        'two_two'=>array(
            'two_two_one'=>'value',
            'two_two_two'=>'value',
        )
    )
);
$remove_elements = array(
    'one' =>array(
        'one_one',
        'one_two'=> array(
            'one_two_one',
        )
    ),
    'two'
);

The output I would like would look like this.

$result = array(
    'one' =>array(
        'one_two'=> array(
            'one_two_two'=>'value',
        )
    )
);

I have tried array_diff but I get a "Array to string conversion" error, I assume this is because they are nested arrays.

i created a function but ii cant get it to work.

function arrayRecursiveUnset($array_1, $array_2) {

  foreach ($array_1 as $array_1_key => $array_1_value) {

    if (array_key_exists($array_1_key, $array_2)) {

      if (is_array($array_1_value)) {

        $array_1[$array_1_key] = arrayRecursiveUnset($array_1_value, $array_2[$array_1_key]);

      } else {
        unset($array_1[$array_1_key]);
      }
    } 
  }
  return $array_1;
} 
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-09-17 15:17
    关注

    It hasn't been thoroughly tested but it seems to be working for what I need it for. hope this helps someone.

    function arrayRecursiveUnset($array_1, $array_2) {
    
        foreach ($array_1 as $array_1_key => $array_1_value) {
    
            if (array_key_exists($array_1_key, $array_2)) {
    
                if (is_array($array_1_value)) {
    
                    $array_1[$array_1_key] = arrayRecursiveUnset($array_1_value, $array_2[$array_1_key]);
    
                } else {
    
                    unset($array_1[$array_1_key]);
                }
            } else if (in_array($array_1_key, $array_2)){
                unset($array_1[$array_1_key]);
            } 
        }
        return $array_1;
    } 
    
    
    $result = arrayRecursiveUnset(  $all_data  , $remove_elements);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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