dongzhaobai5982 2015-11-21 08:14
浏览 26
已采纳

从数组中删除双重条目

I have the following array in php:

[0] => Array(
  (
    [post_id] => 492,
    [user_id] => 1
  )
[1] => Array(
  (
    [post_id] => 501,
    [user_id] => 1
  )
[2] => Array(
  (
    [post_id] => 568,
    [user_id] => 13
  )
[3] => Array(
  (
    [post_id] => 897,
    [user_id] => 13
  )

What I want to do, is to delete the ones where the user_id already exists. So the result should look like this:

[0] => Array(
  (
    [post_id] => 492,
    [user_id] => 1
  )
[1] => Array(
  (
    [post_id] => 568,
    [user_id] => 13
  )

I need an array, in which every user_id only exists one time.

array_unique() doesn't work for this example. Any ideas?

Thanks!

  • 写回答

2条回答 默认 最新

  • dtqysxw4659 2015-11-21 08:20
    关注

    You can loop through and find unique values as you go:

    $exists = array();
    foreach($items as $key => $item) {
        if(!in_array($item['user_id'], $exists)) {
            $exists[] = $item['user_id'];
        } else {
            unset($items[$key]);
        }
    }
    

    This will unset any arrays that already exist in the $exists array.

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

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM