dongqian7545 2018-08-24 05:37
浏览 32
已采纳

PHP - 过滤数组以从子数组中删除具有非相似键的值

I have an array like below. This is coming from a centralised database and I have no way of knowing beforehand what the actual array will contain. I want to compare the sub-arrays on keys and that is why want to delete the keys which are not present is all sub-arrays.

Array (
    [0] => Array
        (
            [a] => 
            [b] => 8
            [c] => 1
            [d] => taille-8
            [e] => 
            [k] => taill
        )

    [1] => Array
        (
            [a] => 
            [b] => 7
            [c] => 2
            [d] => taille-7
            [f] =>
            [k] => tafefef
        )

    [2] => Array
        (
            [a] => ce
            [b] => 34
            [c] => 2
            [d] => taille-34
            [g] => dee
            [k] => tacefef
        ) );

I want to delete the keys which are not repeating in all sub-arrays. In the above example they are 'e', 'f' and 'g'. This needs to happen dynamically.

Array (
    [0] => Array
        (
            [a] => 
            [b] => 8
            [c] => 1
            [d] => taille-8
            [k] => taill
        )

    [1] => Array
        (
            [a] => 
            [b] => 7
            [c] => 2
            [d] => taille-7
            [k] => tafefef
        )

    [2] => Array
        (
            [a] => ce
            [b] => 34
            [c] => 2
            [d] => taille-34
            [k] => tacefef            
        ) );

Any suggestion is appreciated.

  • 写回答

2条回答 默认 最新

  • drctyr2869 2018-08-24 05:50
    关注

    You can splice the array and loop the rest.
    In the loop I overwrite the $new with whatever is the same in each iteration.
    The end should be what is matching throughout the full array.

    Then we need to use the new and as a template to remove the other items in the array, so we loop again and intersect again but overwrite $arr this time.

    $arr =[['a' => 1, 'b' => 2, 'c' => 3],
           ['a' => 1, 'c' => 3],
           ['c' => 3]];
    
    $new = $arr[0];
    
    foreach($arr as $sub){
        $new = array_intersect_key($new, $sub);
    }
    foreach($arr as &$sub){
        $sub =array_intersect_key($sub, $new);
    }
    unset($sub);
    Var_dump($arr);
    

    Output

    array(3) {
      [0]=>
      array(1) {
        ["c"]=>
        int(3)
      }
      [1]=>
      array(1) {
        ["c"]=>
        int(3)
      }
      [2]=>
      &array(1) {
        ["c"]=>
        int(3)
      }
    }
    

    https://3v4l.org/oM3M1l

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

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流