phparraysmultidimensional-arrayfilterduplicates

How to remove duplicate elements from each row of a 2d array?


"2017-08-31":["5948a0dd21146a43fdcfef5a","5948a0dd21146a43fdcfef5a"]
"2017-08-22":["5948a0dd21146a43fdcfef5a"]
"2017-08-09":["59461ceae6179b19403c6a19","59461ceae6179b19403c6a19"]
"2017-08-08":["59461ceae6179b19403c6a19","59461ceae6179b19403c6a19"]

I have an array like this, key is a date and multiple value associated with that date, but I need unique value with that key.how to do that ? I've tried with array_unique but no luck!

My desired result:

"2017-08-31":["5948a0dd21146a43fdcfef5a"]
"2017-08-22":["5948a0dd21146a43fdcfef5a"]
"2017-08-09":["59461ceae6179b19403c6a19"]
"2017-08-08":["59461ceae6179b19403c6a19"]

Solution

  • Just use array_map and array_unique together.

    <?php
    $a = json_decode('{"2017-08-31":["5948a0dd21146a43fdcfef5a","5948a0dd21146a43fdcfef5a"],
                       "2017-08-22":["5948a0dd21146a43fdcfef5a"],
                       "2017-08-09":["59461ceae6179b19403c6a19","59461ceae6179b19403c6a19"],
                       "2017-08-08":["59461ceae6179b19403c6a19","59461ceae6179b19403c6a19"]}', true);
    
    echo json_encode(array_map("array_unique", $a));