PHP 在 while 循环后回显数组值

标签 php mysql arrays while-loop echo

如何在 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/

相关文章:

php - 根据特定客户端 ID 过滤对 Controller 操作的访问的最佳方法

MYSQL使用多个主键的重复键语法

c - 二维数组获得不需要的额外元素

c++ - STL 是否包含适用于数组的迭代器?

c - qsort记录(char数组)按降序排列

php - Laravel 5.2 查找基于多对多关系的模型

太平洋/斐济的 Php 夏令时问题

php - Flight框架如何避免未定义索引错误

MySQL 查询 : Getting the most recent forum post

php - 需要帮助 INSERT 记录 MySQL DB