【问题标题】:Odd response from accessing JSON variable访问 JSON 变量的奇怪响应
【发布时间】:2013-09-23 15:56:46
【问题描述】:

我有这个代码:

<?php
$jsonurl = "http://api.wipmania.com/json";
$jsonfgc = file_get_contents($jsonurl);
$json = json_decode($jsonfgc, true);

foreach ( $json["address"] as $address => $country_code )
    {   
      echo $address["country_code"];
    }
?>

但是,当我打印出来时,我只得到“cccccr”。我只尝试echoing $country_code,但我得到“North AmericaNA-United StatesUS-”。有什么帮助吗?

【问题讨论】:

    标签: php file-get-contents json


    【解决方案1】:

    如果您实际上是在尝试获取国家/地区代码,请执行以下操作:

    echo $json['address']['country_code'];
    

    那里不需要循环。


    我尝试只是回显 $country_code 但我得到“North AmericaNA-United StatesUS-”。有什么帮助吗?

    关于为什么会发生这种情况的解释:

    您可能没有在代码中添加任何换行符。所以它看起来好像是一个字符串。其实不然。

    试试:

    foreach ( $json["address"] as $address => $country_code )
    {   
        echo $country_code."<br/>\n";
    }
    

    输出应该是:

    North America
    NA
    -
    United States
    US
    -
    

    See the difference!

    【讨论】:

    • 谢谢!但是,为什么会发生循环?当我尝试您的第二个代码时,我得到“USUSUSUSUSUS”。
    • @DayloStar:正如我在回答中提到的那样,如果您只需要国家代码,则不需要循环。只需在循环外回显它,它就会打印一次US
    • 谢谢,你真的帮了大忙。
    【解决方案2】:

    为什么你使用$address 作为数组它只是一个索引。

    如果你只想要国家代码

    用途:

    //foreach ( $json["address"] as $address => $country_code )
    //{   
      echo $json["address"]["country_code"];
    //}
    

    【讨论】:

    • 我使用json_decode($jsonfgc, true); 将json解码为一个数组。
    • 它必须是一个数组但是 $address["country_code"];是不可能的,因为在 foreach il $address 只是一个变量
    【解决方案3】:

    尝试先打印出来,这样会更容易弄清楚。 (当然用于调试)

    var_dump($json); // or print_r( $json ); if you want
    

    要打印键和值,您可以使用:

    foreach( $json['address'] AS $index => $value ) {
      echo "$index - $value<br />";
    }
    

    【讨论】:

      【解决方案4】:
      <?php
      $jsonurl = "http://api.wipmania.com/json";
      $jsonfgc = file_get_contents($jsonurl);
      $json = json_decode($jsonfgc, true);
      
      echo $json["address"]["country_code"]; //if json return single value
      //if return multiple then execute it
      foreach ( $json as $key => $val )
          {   
            if($key=="address"){
            echo $json[$key]['country_code'];
            };
      
          }
      ?>
      

      【讨论】:

      • 谢谢!我会赞成你的回答,但我没有足够的代表.. :)
      【解决方案5】:

      这里不需要foreach。只需使用:

      echo $json["address"]["country_code"];
      

      请注意,在 PHP 5.4 及更高版本中,您的代码实际上会生成警告:“警告:非法字符串偏移 'country_code'”。在您的 foreach 循环(枚举对象中的所有属性)中,$address 是一个字符串(属性名称),而不是一个数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多