在PHP中迭代关联数组不会打印出值

时间:2019-05-25 06:56:58

标签: php arrays

我正在为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>");
}

1 个答案:

答案 0 :(得分:1)

这是因为在这一部分$MovieCollection是一个数组数组,如果您想回显作为数组的$value,您将执行一个Array to string conversion,它不起作用。

您可能要做的是使用另一个foreach来显示每个数组的值:

foreach ($MovieCollection as $value) {
    foreach ($value as $k => $v) {
        echo($k .": " . $v ."<br>");
    }
}

查看Php demo