从数组中获取值

时间:2011-09-06 06:21:43

标签: php arrays

我有一个从JSON字符串解析的PHP数组,如下所示:

array(1) {
  ["ResultSet"]=>
  array(7) {
    ["version"]=>
    string(3) "1.0"
    ["Error"]=>
    int(0)
    ["ErrorMessage"]=>
    string(8) "No error"
    ["Locale"]=>
    string(5) "us_US"
    ["Quality"]=>
    int(99)
    ["Found"]=>
    int(1)
    ["Results"]=>
    array(1) {
      [0]=>
      array(29) {
        ["quality"]=>
        int(72)
        ["latitude"]=>
        string(9) "34.746479"
        ["longitude"]=>
        string(10) "-92.289589"
        ["offsetlat"]=>
        string(9) "34.746479"
        ["offsetlon"]=>
        string(10) "-92.289589"
        ["radius"]=>
        int(500)
        ["name"]=>
        string(20) "34.746479,-92.289589"
        ["line1"]=>
        string(13) "State Capitol"
        ["line2"]=>
        string(22) "Little Rock, AR  72201"
        ["line3"]=>
        string(0) ""
        ["line4"]=>
        string(13) "United States"
        ["house"]=>
        string(0) ""
        ["street"]=>
        string(13) "State Capitol"
        ["xstreet"]=>
        string(0) ""
        ["unittype"]=>
        string(0) ""
        ["unit"]=>
        string(0) ""
        ["postal"]=>
        string(5) "72201"
        ["neighborhood"]=>
        string(0) ""
        ["city"]=>
        string(11) "Little Rock"
        ["county"]=>
        string(14) "Pulaski County"
        ["state"]=>
        string(8) "Arkansas"
        ["country"]=>
        string(13) "United States"
        ["countrycode"]=>
        string(2) "US"
        ["statecode"]=>
        string(2) "AR"
        ["countycode"]=>
        string(0) ""
        ["hash"]=>
        string(0) ""
        ["woeid"]=>
        int(12789127)
        ["woetype"]=>
        int(11)
        ["uzip"]=>
        string(5) "72201"
      }
    }
  }
}

我试图得到像这样的woeid参数的值:

 foreach ($data["ResultSet"] as $key => $val) 
 {
    echo $val["woeid"]."<br />";
 }  

但由于某种原因,它没有获得价值。我做错了吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

您需要$data['ResultSet']['Results'],而不是$data['ResultSet']

答案 1 :(得分:0)

第一个$key => $val将是version => 1.0。强1.0不是数组而且没有数据。

我不会尝试解码大型数据结构的单行表达式,但您需要导航到您想要的数据实际显示的位置。

答案 2 :(得分:0)

$ data [“ResultSet”]是一个对象,实际结果在$ data [“ResultSet”] [“Results”]中。所以使用:

 foreach ($data["ResultSet"]["Results"] as $key => $val) 
 {
    echo $val["woeid"]."<br />";
 }