多维数组未返回正确的值



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

$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

你知道我做错了什么吗?

array_keys($states)正在返回

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

因此,foreach循环只回显每个状态的第一个字符。循环通过整个阵列而不仅仅是密钥:

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

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

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

如果你想同时循环键和值,试试这个

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

您可以使用两个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

只是:

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

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

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

相关内容

  • 没有找到相关文章

最新更新