我有一個 php 代碼將產品添加到會話中,但它沒有按預期工作,下面是我的代碼:<?phpsession_start();include 'db.php';$status = 1;if (isset($_POST['id']) && $_POST['id']!=""){ $id = $_POST['id']; $sql = "SELECT * FROM website_tree WHERE id = '$id' "; $result = mysqli_query($link, $sql); $row = mysqli_fetch_array($result); $id = $row['id']; $name = $row['name']; $price = $row['price']; $image = $row['image']; $cartArray = array( 'id'=>$id, 'name'=>$name, 'price'=>$price, 'image'=>$image, 'quantity'=>1 ); if(empty($_SESSION["shopping_cart"]['product'])) { $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray); $status = 1; }else{ $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray); $status = 1; }}echo json_encode(array("status"=>$status)); ?>我收到這個警告: array_push() expects parameter 1 to be array, null誰能幫我糾正我的代碼?
2 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
$_SESSION["shopping_cart"]['product']如果未定義(未設置)則定義。
session_start();
include 'db.php';
$status = 1;
// here
if (!isset($_SESSION["shopping_cart"]['product'])) {
$_SESSION["shopping_cart"]['product'] = [];
}
// more code here...
$cartArray = array(
'id'=>$id,
'name'=>$name,
'price'=>$price,
'image'=>$image,
'quantity'=>1
);
// `array_push` works with array by reference
// so there's no need to reassign this variable
array_push($_SESSION["shopping_cart"]['product'], $cartArray);
$status = 1;

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
您的代碼看起來不錯,但您需要將 session_start() 放在 <?php 標記之后。
確保此函數之前沒有任何輸出(甚至是空格符號等)。
所以改變:
<?php session_start();
到:
<?php session_start();
- 2 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
0/150
提交
取消