【问题标题】:Want to print one statename only once只想打印一个州名一次
【发布时间】:2016-07-27 11:24:16
【问题描述】:

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

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

【问题讨论】:

  • 请不要大喊大叫。

标签: php json


【解决方案1】:

假设您只想要州名(您的问题表明您这样做),您可以大大简化如下:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      相关资源
      最近更新 更多