Dodinas Dodinas - 6 months ago 138
PHP Question

Array Unique with Associative Array - Remove Duplicates

I've got an associative array with some duplicate items. For example, I have:

<?
$group_array = array('user_id'=>array(), 'user_first'=>array());


Which outputs something like below:

Array
(
[user_id] => Array
(
[0] => 594
[1] => 597
[2] => 594
)

[user_first] => Array
(
[0] => John
[1] => James
[2] => John
)
)


I'd like to sanitize this entire array so that only the user John will show up once (based on user_id).

I've tried the following:

<?php
$unique = array_unique($group_array);
print_r($unique);


But it does not appear to work. Any other ideas how I can remove the duplicate items in the array?

Any help would be great!

Answer

Another approach would be to find the unique user_ids, and importantly their array keys, then keep only the corresponding values from each of the columns.

$group_array = array(
    'user_id'    => array(594,    597,     594,    598   ),
    'user_first' => array('John', 'James', 'John', 'John'),
);

// Find unique user_ids
$uniques = array_unique($group_array['user_id']);

// Keep only the uniques
foreach ($group_array as $column => $collection) {
    $group_array[$column] = array_intersect_key($collection, $uniques);
}

print_r($group_array);