带索引的数组“";在数据库检索之后


Array with index "" after a database retrieval

我正在练习PHP,试图了解其来龙去脉。这么做,我正在做一个小网店。其中一个功能是登录后检索shoppingcart。这很有效,但不知何故,在数组订单中出现了一个索引为"的项目。我不知道它是如何到达那里的,也不知道如何(如果我不能阻止这种情况发生)将它从数组中删除。。。我试着解开它,但没有效果。这是创建$_SESSION['Bestellen']数组的代码:

        $query = "SELECT * FROM orders WHERE user_id = ".$_SESSION['user_id'];
        $result = mysqli_query($db, $query);
        while ($row = mysqli_fetch_assoc($result)){
            foreach($row as $key => $value){ 
                $order[$key] = $value;                  
                $_SESSION['Bestellen'][$order['product_id']]['aantal'] = $order['ammount'];
                $_SESSION['Bestellen'][$order['product_id']]['product_id'] = $order['product_id'];
            }                       
            $query = "SELECT product_name, price FROM products WHERE product_id = ".$order['product_id'];
            $result2 = mysqli_query($db, $query);
            while ($row2 = mysqli_fetch_assoc($result2)){
                foreach($row2 as $key2 => $value2){
                    $item[$key2] = $value2;
                    $_SESSION['Bestellen'][$order['product_id']]['product_name'] = $item['product_name'];
                    $_SESSION['Bestellen'][$order['product_id']]['price'] = $item['price'];
                }
            }
        }

我在数据库中订购了两个项目,但数组最终有第三个项目(数组中的第一个),没有任何值,并被索引为":

array(3) {
  [""]=>
  array(2) {
    ["aantal"]=>
    NULL
    ["product_id"]=>
    NULL
  }
  [1]=>
  array(4) {
    ["aantal"]=>
    string(2) "10"
    ["product_id"]=>
    string(1) "1"
    ["product_name"]=>
    string(6) "boutje"
    ["price"]=>
    string(4) "0.32"
  }
  [3]=>
  array(4) {
    ["aantal"]=>
    string(1) "7"
    ["product_id"]=>
    string(1) "3"
    ["product_name"]=>
    string(7) "schroef"
    ["price"]=>
    string(4) "0.15"
  }
}

它是怎么到达那里的?我该如何防止这种情况发生?

看起来$order['product_id']丢失或为空。请检查数据库以确保行product_id存在并且不为空。

可能只是它还不存在。。

        foreach($row as $key => $value){ 
            $order[$key] = $value;                  
        }
        $_SESSION['Bestellen'][$order['product_id']]['aantal'] = $order['ammount'];
        $_SESSION['Bestellen'][$order['product_id']]['product_id'] = $order['product_id'];

在会话中尝试使用变量之前,循环查看结果并设置$order数组。

此外,请确保首先初始化$order数组,否则可能会收到未设置的变量通知。。

$order = []; //somewhere above your loop