打印键和php multidiamensional数组的值

时间:2016-08-11 22:38:45

标签: php multidimensional-array

我是php初学者。我有一个多维数组如下。

$mainArray = array();

$mainArray['apple'] = array();
$mainArray['apple'][0] = 'fruit';
$mainArray['apple'][1] = 'red';

$mainArray['banana'] = array();
$mainArray['banana'][0] = 'fruit';
$mainArray['banana'][1] = 'yellow';

$mainArray['spinach'] = array();
$mainArray['spinach'][0] = 'vegetable';
$mainArray['spinach'][1] = 'green';

我想获得如下输出:

apple is fruit
apple is red
banana is fruit
banana is yellow
spinach is vegetable
spinach is green

我正在努力在PHP中使用forforeach循环来查找第一个密钥apple, banana or spinach ..任何帮助都将不胜感激。非常感谢你

1 个答案:

答案 0 :(得分:0)

foreach ($mainArray as $type => $descriptions) {
    foreach ($descriptions as $description) {
        echo $type . ' is ' . $description, PHP_EOL;
    }
}

如果您需要按特定顺序输出它们,请在使用类似上述示例之类的内容之前对数组进行排序。