想要只打印一个州名

时间:2016-07-27 11:24:16

标签: php json

我的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

我想只打印一个州名打印一次。我怎么能这样做?

2 个答案:

答案 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将删除重复项。

相关问题