PHP Array 删除重复的键值并只显示一个 [英] PHP Array removing the duplicate key value and displaying only one

查看:32
本文介绍了PHP Array 删除重复的键值并只显示一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Array
(
    [0] => Array
        (
            [user_id] => 78
            [post_id] => 3
            [post_user_added_id] => 2
        )

    [1] => Array
        (
            [user_id] => 76
            [post_id] => 8
            [post_user_added_id] => 16
        )

    [2] => Array
        (
            [user_id] => 78
            [post_id] => 9
            [post_user_added_id] => 12
        )

    [3] => Array
        (
            [user_id] => 76
            [post_id] => 9
            [post_user_added_id] => 15
        )

     [4] => Array
         (
             [user_id] => 77
             [post_id] => 9
             [post_user_added_id] => 15
         )

)

这里的想法是,当存在重复的 user_id 时,它只会显示一个?这是预期的结果:

The idea here is that when there is a duplicate user_id, it will just display only one? This is the expected result:

 Array
 (
      [2] => Array
          (
             [user_id] => 78
             [post_id] => 9
             [post_user_added_id] => 12
           )

        [3] => Array
            (
                [user_id] => 76
                [post_id] => 9
                [post_user_added_id] => 15
            )

         [4] => Array
             (
                 [user_id] => 77
                 [post_id] => 9
                 [post_user_added_id] => 15
             )

    )

之所以显示[2]键而不是[0]键或[1]键而不是[3],是因为我想得到重复键的底键.这有点难以解释,但我希望您理解我预期的场景或输出.

The reason why [2] key instead of [0] key or [1] key instead of [3] is displayed because I want to get the bottom key of the duplicate key. It's kinda hard to explain but I hope you understood the scenario or the output that I expected.

您的帮助将不胜感激!谢谢!:)

Your help would be greatly appreciated! Thanks! :)

推荐答案

试试这个:

foreach($arr as $k => $v) 
{
    foreach($arr as $key => $value) 
    {
        if($k != $key && $v['user_id'] == $value['user_id'])
        {
             unset($arr[$k]);
        }
    }
}
print_r($arr);

这篇关于PHP Array 删除重复的键值并只显示一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆