我无法获得保留在$ _SESSION变量中的值

时间:2011-06-04 23:46:03

标签: php arrays echo associative indexed

我试图从索引数组中获取值,但是当我使用变量作为索引(它等于数组中的索引)时,它不会出现。我收到Undefined Index错误。为什么会这样?有人知道吗?谢谢!

我有以下代码:

$bookarray = array();
                $books = mysqli_query($db, "SELECT * FROM books");
                while($row = mysqli_fetch_assoc($books)){
                    $bookarray[$row['bookID']] = array(
                        'title' => $row['title'],
                        'author' => $row['author'],
                        'price' => $row['price']
                    );
                }
                echo"<hr>";
                print_r($bookarray);
                echo"<hr>";
                echo $bookarray[5]['title']."<br />";


                foreach($_SESSION['cart'] as $cartedbook){
                    echo $cartedbook;
                    echo $bookarray[$cartedbook]['title'];
                    echo "<br />";
                }

这是输出:

图书


Array
(
[1] => Array
    (
        [title] => Java 2 for Pro Deelopers
        [author] => Michael Morgan
        [price] => 34.99
    )

[2] => Array
    (
        [title] => Installing XAMPP
        [author] => Thomas Down
        [price] => 24.99
    )

[3] => Array
    (
        [title] => Alice Through the Looking Glass
        [author] => Louis Carroll
        [price] => 72.35
    )

[4] => Array
    (
        [title] => Quantum Mechanics in 124 Hours
        [author] => Neils Bohr
        [price] => 24.99
    )

[5] => Array
    (
        [title] => PHP For Fun And Profit
        [author] => Thomas Shenk
        [price] => 49.99
    )

[28] => Array
    (
        [title] => Test
        [author] => Eric Gross
        [price] => 100.00
    )


PHP的乐趣和利润                         5
通知:未定义的索引:                         5 C:\ xampp \ htdocs \ FinalProject \ cart.php 52


                        3
通知:未定义的索引:                         3 C:\ xampp \ htdocs \ FinalProject \ cart.php 52

标题作者价格

2 个答案:

答案 0 :(得分:1)

mysql查询的结果是字符串,即使它们是数据库中的整数。这会导致您的$bookarray通过数字字符串而不是数字索引关联,您可能会尝试使用它们。

尝试将该ID转换为int:

$bookarray[(int) $row['bookID']] = array(

答案 1 :(得分:0)

如果我查看你的问题的来源,似乎在数字之前有一个换行符(因此,它将是"\n5"而不是5,这在逻辑上无法找到),可以你确认一下吗? var_dump($cartedbook);会产生什么?