我是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中使用for
或foreach
循环来查找第一个密钥apple, banana or spinach
..任何帮助都将不胜感激。非常感谢你
答案 0 :(得分:0)
foreach ($mainArray as $type => $descriptions) {
foreach ($descriptions as $description) {
echo $type . ' is ' . $description, PHP_EOL;
}
}
如果您需要按特定顺序输出它们,请在使用类似上述示例之类的内容之前对数组进行排序。