Home > Software engineering >  php how to remove both duplicate associative array if found
php how to remove both duplicate associative array if found

Time:05-23

i have this rows.

$rows = [
    ['user' => 1, 'access' => '342'],
    ['user' => 2, 'access' => '765'],
    ['user' => 3, 'access' => '134'],
    ['user' => 1, 'access' => '342']
];

i manage to remove duplicate eg: user = 1,

$ids = [];
foreach ($rows as $k => $item) {
    if (in_array($item['user'], $ids)){
         unset($rows[$k]);            
    } else {
         $ids[] = $item['user'];
    }    
}

echo json_encode($rows);

the thing is, i want the end result to remove totally the both duplicate. eg: desired output (no more user 1)

[
 {"user":2,"access":"765"},
 {"user":3,"access":"134"}
]

thank you

CodePudding user response:

$rows = [
        ['user' => 1, 'access' => '342'],
        ['user' => 2, 'access' => '765'],
        ['user' => 3, 'access' => '134'],
        ['user' => 1, 'access' => '342']
    ];
    $res = [];
    foreach ($rows as $row) {
        if(!empty($res[$row['user']])) {
            unset($res[$row['user']]);
        } else {
            $res[$row['user']] = $row;
        }
    }
    print_r(array_values($res));

CodePudding user response:

You can use array_unique with SORT_REGULAR option

$rows = [
    ['user' => 1, 'access' => '342'],
    ['user' => 2, 'access' => '765'],
    ['user' => 3, 'access' => '134'],
    ['user' => 1, 'access' => '342']
];

$uniqueRows = array_unique($rows, SORT_REGULAR);

  •  Tags:  
  • php
  • Related