0

I have parsed and decoded a json into a php file. The json is in a format similar to this:

{"name":"John Doe", "records":[{"sample": "sample","fields":{"date":"Sample Date","Sample Field":"Sample value", "id": "sampleid"}}

I have a lot of records that are similar to this in that file. I have been using a foreach loop to return all of the date fields. The loop looks something like:

$records = $records_json['records'];
foreach($records as $record) {
        echo "<option>" . $record['fields']['date'] . "</option>";
}

Right now, this is returning all of the dates. However, there are a lot of duplicate dates, and I only want to return the unique dates (without duplicates). Is there a way to do this?

Matt
  • 85
  • 7

4 Answers4

0

You could use an array where you store the dates and check the new dates against the values in this array to see if the "new" date is in there, if it isn't it is a unique date and should be added to the array.

$records = $records_json['records'];
$uniques = array():
foreach($records as $record) {
    if (!in_array($record['fields']['date'], $uniques)) {
        $uniques[] = $record['fields']['date'];
    }
}
foreach ($uniques as $unique) {
    echo "<option>" . $unique . "</option>";
}
0

Try this code :

<?php
$records_json = '{"name":"John Doe", "records":[{"sample": "sample","fields":{"date":"Sample Date","Sample Field":"Sample value", "id": "sampleid"}}]}';
$arr = json_decode($records_json,TRUE);
$records = $arr['records'];
foreach($records as $record) {
        echo  $record['fields']['date'] ;
}
?>
0

Demo online

 <?php

$json = '{"name":"John Doe", "records":[{"sample": "sample","fields":{"date":"Sample Date","Sample Field":"Sample value", "id": "sampleid"}}]}';

$json  = json_decode($json , true);
$dates = [];

foreach($json['records'] as $record) {
   $date = $record['fields']['date'];
   if(!isset($dates[$date]))
      $dates[]= $date;
}

var_dump($dates);
Maksym Semenykhin
  • 1,924
  • 15
  • 26
-1

You can build a date array and then filter it with array_unique.

<?php

$array  = ['foo', 'foo', 'bar', 'baz'];
$unique = array_unique($array);

var_export($unique);

Output:

array (
  0 => 'foo',
  2 => 'bar',
  3 => 'baz',
)
Progrock
  • 7,373
  • 1
  • 19
  • 25