Thursday, 30 August 2018

PHP unique / group associative array

I would like to remove duplicates for the following array. I want to group by the first value and then rebuild the index.

ie
Array
(
    [0] => Array
        (
            [title] => California
            [state_id] => 1
        )

    [1] => Array
        (
            [title] => California
            [state_id] => 1
        )

    [2] => Array
        (
            [title] => New Mexico
            [state_id] => 2
        )

    [3] => Array
        (
            [title] => Washington
            [state_id] => 3
        )

    [4] => Array
        (
            [title] => Montana
            [state_id] => 4
        )

    [5] => Array
        (
            [title] => Montana
            [state_id] => 4
        )
)

To
Array
(
    [0] => Array
        (
            [title] => California
            [state_id] => 1
        )

[2] => Array
    (
        [title] => New Mexico
        [state_id] => 2
    )

[3] => Array
    (
        [title] => Washington
        [state_id] => 3
    )

[4] => Array
    (
        [title] => Montana
        [state_id] => 4
    )

)

and rebuild key
Array
(
    [0] => Array
        (
            [title] => California
            [state_id] => 1
        )

    [1] => Array
        (
            [title] => New Mexico
            [state_id] => 2
        )

    [2] => Array
        (
            [title] => Washington
            [state_id] => 3
        )

    [3] => Array
        (
            [title] => Montana
            [state_id] => 4
        )

)


$array = array_values(array_combine(array_map(function ($i) { return $i['title']; }, $array), $array));

I.e.
  • extract the title key (array_map)
  • use the extracted titles as keys for a new array and combine it with the old one (array_combine), which de-duplicates the array (keys have to be unique)
  • run the result through array_values, which discards the keys
Broken down:
$keys    = array_map(function ($i) { return $i['title']; }, $array);
$deduped = array_combine($keys, $array);
$result  = array_values($deduped);

For PHP 5.2- you'll need to write the anonymous callback function like this:
array_map(create_function('$i', 'return $i["title"];'), $array)

0 comments:

Post a Comment