我已经将json解析并解码为php文件。json的格式类似如下:
{"name":"John Doe", "records":[{"sample": "sample","fields":{"date":"Sample Date","Sample Field":"Sample value", "id": "sampleid"}}
我在那个文件中有很多类似的记录。我一直使用foreach
循环来返回所有的date
字段。循环看起来像这样:
$records = $records_json['records'];
foreach($records as $record) {
echo "<option>" . $record['fields']['date'] . "</option>";
}
现在,它返回所有的日期。然而,有很多重复的日期,我只想返回唯一的日期(没有重复的)。有办法做到这一点吗?
您可以使用存储日期的数组,并根据该数组中的值检查新日期,以查看是否有"new"日期,如果没有,则为唯一日期,应添加到数组中。
$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>";
}
试试下面的代码:
<?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'] ;
}
?>
在线演示
<?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);
您可以创建一个日期数组,然后使用array_unique进行筛选。
<?php
$array = ['foo', 'foo', 'bar', 'baz'];
$unique = array_unique($array);
var_export($unique);
输出:array (
0 => 'foo',
2 => 'bar',
3 => 'baz',
)