You don't need any custom function calls for this task. Just use array_column()
to assign new temporary keys to each subarray, then reindex the subarrays and print to screen. *this does overwrite earlier occurrences with later ones.
Code: (Demo)
$array=[
['user_id'=>82,'ac_type'=>1],
['user_id'=>80,'ac_type'=>5],
['user_id'=>76,'ac_type'=>1],
['user_id'=>82,'ac_type'=>2],
['user_id'=>80,'ac_type'=>6]
];
var_export(array_values(array_column($array,NULL,'user_id')));
Output:
array (
0 =>
array (
'user_id' => 82,
'ac_type' => 2,
),
1 =>
array (
'user_id' => 80,
'ac_type' => 6,
),
2 =>
array (
'user_id' => 76,
'ac_type' => 1,
),
)
If you want to keep the first occurrences and ignore all subsequent duplicates, this will do:
Code: (Demo) (* this keeps the first occurrences)
$array=[
['user_id'=>82,'ac_type'=>1],
['user_id'=>80,'ac_type'=>5],
['user_id'=>76,'ac_type'=>1],
['user_id'=>82,'ac_type'=>2],
['user_id'=>80,'ac_type'=>6]
];
foreach($array as $a){
if(!isset($result[$a['user_id']])){
$result[$a['user_id']]=$a; // only store first occurence of user_id
}
}
var_export(array_values($result)); // re-index
Output:
array (
0 =>
array (
'user_id' => 82,
'ac_type' => 1,
),
1 =>
array (
'user_id' => 80,
'ac_type' => 5,
),
2 =>
array (
'user_id' => 76,
'ac_type' => 1,
),
)
If you don't mind losing the order of your subarrays, you can use array_reverse()
with array_column()
to retain the first occurrences using temporary keys, then use array_values()
to re-index:
var_export(array_values(array_column(array_reverse($array),NULL,'user_id')));
/*
array (
0 =>
array (
'user_id' => 76,
'ac_type' => 1,
),
1 =>
array (
'user_id' => 82,
'ac_type' => 1,
),
2 =>
array (
'user_id' => 80,
'ac_type' => 5,
),
)
*/