PHP从嵌套数组输出密钥名称

时间:2014-02-20 17:44:46

标签: php arrays wordpress

我有array

$cats = array(
  'guitars' => array (
    'electric-guitars',
    'acoustic-guitars',
    'bass',
    'electro-acoustic',
    'effects-fx-pedals',
    'guitar-amps',
    'classical-guitars',
    'guitar-recording',
    'folk',
    'cases-stands',
    'guitar-care',
    'guitar-accessories'
  ),
  'drums',
  'keyboards',
  'studio',
  'computer',
  'dj-pa',
  'brass',
  'accessories'
);

我正在尝试输出顶级键,因此输出以下内容:

guitars
drums
keyboards
studio
computer
dj-pa
brass
accessories

我正在使用此foreach循环:

foreach($cats as $cat => $cat_name) {
  echo '<div>' . $cat_name . '</div>';
}

但这反过来输出:

Array
drums
keyboards
studio
computer
dj-pa
brass
accessories

如果有人能提供帮助,我们将不胜感激!

1 个答案:

答案 0 :(得分:4)

您正在尝试输出值,而不是键。使用foreach(... as ... => ...)时,语法为foreach($array as $key => $value)。您的变量名称是向后的。此外,您需要使用is_array()来确定输出是什么,因为您在使用键名与值时不一致:

foreach($cats as $cat_name => $cat) {
    if(is_array($cat)) { // guitars
        echo '<div>' . $cat_name . '</div>';
    }
    else { // the other values have numeric keys
        echo '<div>' . $cat . '</div>';
    }
}

输出(为了便于阅读,省略了标签):

guitars
drums
keyboards
studio
computer
dj-pa
brass
accessories