-4
"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!

FightForJustice
  • 335
  • 4
  • 16
  • 1
    Can you show the result which is expected? – Neodan Sep 06 '17 at 09:37
  • 4
    show us what you have tried – B. Desai Sep 06 '17 at 09:37
  • 1
    As above, you need to define your problem better to get help - it looks like you could just take the 1st result from all the subarrays, but that might not be the case - you need to clarify – Steve Sep 06 '17 at 09:38
  • `"2017-08-31":["5948a0dd21146a43fdcfef5a"] "2017-08-22":["5948a0dd21146a43fdcfef5a"] "2017-08-09":["59461ceae6179b19403c6a19"] "2017-08-08":["59461ceae6179b19403c6a19"]` @Neodan – FightForJustice Sep 06 '17 at 09:38
  • so each data key will contain a single element array? Will your source array always contain duplicates, or could a date key contain an array with non duplicate values? If so, which value gets kept? Or perhaps your output could contain multiple elements per key if they are unique? – Steve Sep 06 '17 at 09:41

3 Answers3

4

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));
Neodan
  • 5,154
  • 2
  • 27
  • 38
2
$array = your array   
$array = array_map(function($val){return array_unique($val);}, $array);
1

You better do this using SQL if it's possible. Otherwise, you can try this:

$array = array_unique($array, SORT_REGULAR);
Mohamed Chaawa
  • 918
  • 1
  • 9
  • 23