多维数组未返回正确的值

时间:2016-07-27 15:35:56

标签: php arrays multidimensional-array

我有一个多维数组,我正在尝试使用,这是它的样子。

$states = array(
"California" => array(
    "state" => "California",
    "abbr" => "CA",
    "city" => "Sacramento",
    "county" => "Sacramento",
    "zip" => "95632"
),
"Washington" => array(
    "state" => "Washington",
    "abbr" => "WA",
    "city" => "Seattle",
    "county" => "King",
    "zip" => "98101"
),
"Texas" => array(
    "state" => "Texas",
    "abbr" => "TX",
    "city" => "San Antonio",
    "county" => "Bexar",
    "zip" => "78251"
),
"Florida" => array(
    "state" => "Florida",
    "abbr" => "FL",
    "city" => "Orlando",
    "county" => "Orange",
    "zip" => "32801"
),
);

当我运行foreach循环从数组的第一级获取密钥时,我得到预期的输出

California Washington Texas Florida

但是我需要访问数组的第二级。例如,我需要California ['abbr']所以这是我运行的代码:

foreach (array_keys($states) as $state) {
    echo $state['abbr'];
}

而不是

CA WA TX FL 
像我期望的那样

C W T F

关于我做错的任何想法?

5 个答案:

答案 0 :(得分:1)

您可以使用两个foreach来访问每个城市(数组)中的元素。这不是最快的方式,但知道它很好。

// access the first layer
foreach($states as $state)
{
  // access the second layer
  foreach($state as $key => $element)
  {
    // if the key is equal to 'abbr', echo it's value
    echo ($key == 'abbr') ? $state[$key] : '';
    echo '  ';
  }
}

这将输出:

  

CA WA TX FL

答案 1 :(得分:1)

foreach(array_keys($states) as $state) {
    echo $state;
}

将回显键,因为你循环键而不是数组。要获得缩写,您应该

foreach($states as $state) {
    echo $state['abbr'];
}

如果您想同时循环键和值,请尝试使用

foreach($states as $key=>$state) {
    echo "$key: {$state['abbr']}";
}

答案 2 :(得分:1)

array_keys($states)正在返回

 array("California", "Washington", "Texas", "Florida")

因此foreach循环只回显每个州的第一个字符。遍历整个数组而不仅仅是键:

foreach ($states as $name => $details) {
    echo $details['abbr'];
}

答案 3 :(得分:0)

只需:

foreach($states as $state) {
     foreach($state as $v) {
         echo $v['abbr'];
     }
}

答案 4 :(得分:0)

仅删除array_keys。你需要该数组的整个元素,而不仅仅是数组的键。

foreach ($states as $state)
{
    echo $state['abbr'];
}