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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀