只想打印一次一个州名称


Want to print one statename only once

我的PHP代码

<?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

我想只打印一次一个州名称。我该怎么做?

假设你只想要状态名称(你的问题表明你想要),你可以极大地简化如下:

$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将为每个数组条目返回"StateName"条目,array_unique将删除重复项。

试试这个:

$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'];
}