Question

I've got the following array of data:

Array
(
    [0] => Array
        (
            [id] => 1
            [tag] => tag-a
        )

    [1] => Array
        (
            [id] => 1
            [tag] => tag-b
        )

    [2] => Array
        (
            [id] => 4
            [tag] => tag-a
        )
)

Where there are duplicate IDs I want to refactor tag so it's formatted like this:

Array
(
    [0] => Array
        (
            [id] => 1
            [tags] => Array
                (
                    [0] => tag-a
                    [1] => tag-b
                )
        )

    [1] => Array
        (
            [id] => 4
            [tags] => Array
                (
                    [0] => tag-a
                )
        )
)

I've been able to get something working by looping through a 'duplicate report'. But wonder if there's a more efficient way to achieve this array structure?

Was it helpful?

Solution

  1. Convert source array to hash table (key => value array).
  2. Build desired result array from hash table.

Implementation:

$result = array();
foreach ($array as $el) {
    if (!isset($result[$id = $el['id']])) $result[$id] = array();
    $result[$id][] = $el['tag'];
}

$result = array_map(
    function ($id, $tags) { return array('id' => $id, 'tags' => $tags); },
    array_keys($result), array_values($result)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top