Search code examples
phparraysarray-unique

Get unique array for $key


I have the following code:

$keys = array('2', '2', '6', '10', '10', '10', '13', '13', '13', '13', '13', '13', '13', '13', '13', '13', '15', '16', '18', '18', '18', '18', );
$values = array('1712', '1712', '1977', '231', '245', '245', '11', '11', '1121', '1121', '1121', '141', '144', '144', '145', '16', '1980', '153', '153', '171', '171', '183');
$result = array();
foreach ($keys as $i => $k){
    $result[$k][] = $values[$i];
}
print_r($result);

Which outputs:

Array (
    [2] => Array ([0] => 1712 [1] => 1712 )
    [6] => Array ([0] => 1977)
    [10] => Array ([0] => 231 [1] => 245 [2] => 245)
    [13] => Array ([0] => 11 [1] => 11 [2] => 1121 [3] => 1121 [4] => 1121 [5] => 141 [6] => 144 [7] => 144 [8] => 145 [9] => 16)
    [15] => Array ([0] => 1980)
    [16] => Array ([0] => 153)
    [18] => Array ([0] => 153 [1] => 171 [2] => 171 [3] => 183)
)

I would like the "sub arrays" to be unique to each key like the following output - (unique arrays):

Array (
    [2] => Array ([0] => 1712)
    [6] => Array ([0] => 1977)
    [10] => Array ([0] => 231 [1] => 245)
    [13] => Array ([0] => 11 [1] => 1121 [2] => 141  [3] => 144 [4] => 145 [5] => 16)
    [15] => Array ([0] => 1980)
    [16] => Array ([0] => 153)
    [18] => Array ([0] => 153 [1] => 171 [2] => 183)
)

Solution

  • Use array_unique via array_map

    $result = array_map('array_unique', $result);