Thursday, 6 September 2018

Array PHP removes the value of the duplicate key and displays only one

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
         )

)

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
             )

    )

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! :)

Try this :
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);

0 comments:

Post a Comment