douaoj0994 2016-02-06 18:03
浏览 143
已采纳

数组合并和删除重复值

I have this foreach loop that outputs the below array, and I'm having a senior moment, I need it to return one array with no duplicate values, and I just can't it right.

foreach ( $post_groups as $post_group => $id ) {
    group = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $id), ARRAY_A);
    $groups[$group['group_name']] = $group['group_name'] = unserialize( $group['group_users'] );
}

output:

array(2) {
    ["Registered Users"]=>
    array(1) {
    [0]=>
    string(1) "2"
  }
  ["Admin Users"]=>
  array(2) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
  }
}

Cheers

  • 写回答

2条回答 默认 最新

  • ds15812330851 2016-02-06 18:10
    关注

    I believe the following is what you're after. Simply merge the arrays together and then ensure the result is unique.

    $userIds = [
        'Registered Users' => array(1,2,3),
        'Admin Users' => array(3,4,5),
    ];
    
    $allUserIds = array_unique(call_user_func_array('array_merge', $userIds));
    
    var_dump($userIds);
    /*
    array(2) {
      ["Registered Users"]=>
      array(3) {
        [0]=>
        int(1)
        [1]=>
        int(2)
        [2]=>
        int(3)
      }
      ["Admin Users"]=>
      array(3) {
        [0]=>
        int(3)
        [1]=>
        int(4)
        [2]=>
        int(5)
      }
    }
    */
    
    var_dump($allUserIds);
    /*
    array(5) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
      [4]=>
      int(4)
      [5]=>
      int(5)
    }
    */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示