如何在 while 循环后回显值。如果我在下面的代码中进行回显,它会显示 undefined index 。
$sql_cast = "SELECT *
FROM
title_cast
INNER JOIN title ON (title_cast.id_title = title.id)
INNER JOIN `cast` ON (title_cast.id_cast = `cast`.id)
WHERE
title_cast.id_title = '1'";
$result_cast = mysql_query($sql_cast) or die('log error with' .mysql_error());
$cast = array();
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
最佳答案
在 while 循环中,您可以使用 $cast[]
语法设置转换数组内容。这将创建一个数字索引,从 0 开始,然后是 1,依此类推,因此您将创建一个如下所示的数组:
$cast = array(
0 => array('id' => $id, 'name' => $name, 'img' => $poster),
1 => array('id' => $id, 'name' => $name, 'img' => $poster)
);
您需要包含要回显的数组的数字键。例如,如果您想回显第一行:
echo $cast[0]['id']; // Echo the id of the first result
如果要回显所有行,请使用 foreach
:
foreach($cast as $row) {
echo $row['id'];
}
关于PHP 在 while 循环后回显数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9125969/