为什么我会收到通知:未定义的偏移量:1 以及如何更正它


Why am I getting Notice: Undefined offset: 1 and how can I correct it?

为什么我在这里得到一个未定义的偏移量?我能够在另一个页面中成功地做一个循环,做类似的事情。

我在它说的行上收到错误

$subTotal = $subTotal + $totalPrice[$i];

在 while 循环内。

      $totalPrice = [];
      $i = 0;
      while($result = mysqli_fetch_assoc($runquery))
        {
            $id = $value;
            $title = $result['gme_title'];
            $price = $result['gme_price'];
            $quantity = $_POST['quantity'][$id];
            echo "<tr>";
                echo "<td>$title</td>";
                echo "<td>$id</td>";        
                echo "<td>$quantity</td>";
                echo "<td>$price</td>";
            echo "</tr>";
            $totalPrice[$i] = $quantity * $price;
            $i++;
            }
            $subTotal = 0;
            while($i > 0)
            {
                $subTotal = $subTotal + $totalPrice[$i];
                $i--;
            }
            echo "<tr>";
                echo "<td colspan='"3'" class='"align'">Total:</td>";
                echo "<td>$subTotal</td>";
            echo "</tr>";

查询中必须只返回一个项目,这使数组中的$totalPrice数组中只有一个条目(索引为 0)。当它试图查找$totalPrice[1]时,它会告诉你它不存在。

您可以跳过第二个 while 循环,只使用 array_sum 函数。

$subtotal = array_sum($totalPrice); 

一般来说,你也可以跳过做所有$i的事情,这是不必要的。

在第一个循环结束时,i指向最后一个数组元素。

只需在尝试访问第二个循环中的元素之前执行i--即可。

就代码而言,您实际上不需要再次浏览数组,因为array_sum会为您完成这项工作。