<?php
$url = 'https://data.gov.in/api/datastore/resource.json?resource_id=7eca2fa3-d6f5-444e-b3d6-faa441e35294&api-key=ac232a3b2845bbd5be2fc43a2ed8c625&filters[StateName]=MAHARASHTRA&sort[StateName]=asc&limit=5';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['records'] as $item) {
print $item['StateName'];
print '<br>';
}
MAHARASHTRA
MAHARASHTRA
MAHARASHTRA
MAHARASHTRA
MAHARASHTRA
MAHARASHTRA
我想只打印一个州名打印一次。我怎么能这样做?
答案 0 :(得分:0)
试试这个:
$content = file_get_contents($url);
$json = json_decode($content, true);
$temp = array();
foreach($json['records'] as $item) {
if(!in_array($item['StateName'],$temp)) {
print $item['StateName'];
print '<br>';
}
$temp = $item['StateName'];
}
答案 1 :(得分:0)
假设您只需要状态名称(您的问题表明您这样做),您可以按如下方式大大简化:
$content = file_get_contents($url);
$json = json_decode($content, true);
$stateNames = array_unique(array_column($json['records'],"StateName"));
echo implode("<br>",$stateNames)."<br>";
array_column
将返回&#34; StateName&#34;每个数组条目的条目和array_unique
将删除重复项。