我正在为php中的数组尝试以下代码,我创建了一个关联数组,打印出值并将其添加到数组中-再次打印出来。这可行,但是如果我尝试使用foreach ($MovieCollection as $key => $value)
,则它不会打印出值。为什么不这样做?
$myArray = array("Star Wars", "The Shining");
foreach ($myArray as $val)
{
echo("Movie: " . $val ."<br>");
}
$MovieCollection = array();
$MovieCollection[] = array('title' => 'Star Wars', 'description' =>'classic');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
$MovieCollection[] = array('title' => 'The shinning', 'description' =>'creepy');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
echo("<br><br>");
// This does not print the values?
foreach ($MovieCollection as $key => $value)
{
echo($key .": " . $value ."<br>");
}
答案 0 :(得分:1)
这是因为在这一部分$MovieCollection
是一个数组数组,如果您想回显作为数组的$value
,您将执行一个Array to string conversion
,它不起作用。
您可能要做的是使用另一个foreach来显示每个数组的值:
foreach ($MovieCollection as $value) {
foreach ($value as $k => $v) {
echo($k .": " . $v ."<br>");
}
}
查看Php demo