将数组数据推入会话时出错

我有一个 php 代码将产品添加到会话中,但它没有按预期工作,下面是我的代码:


<?php

session_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


谁能帮我纠正我的代码?


Cats萌萌
浏览 113回答 2
2回答

达令说

$_SESSION["shopping_cart"]['product']如果未定义(未设置)则定义。session_start();include 'db.php';$status = 1;// hereif (!isset($_SESSION["shopping_cart"]['product'])) {&nbsp; &nbsp; $_SESSION["shopping_cart"]['product'] = [];}// more code here...$cartArray = array(&nbsp; &nbsp; 'id'=>$id,&nbsp; &nbsp; 'name'=>$name,&nbsp; &nbsp; 'price'=>$price,&nbsp; &nbsp; 'image'=>$image,&nbsp; &nbsp; 'quantity'=>1);// `array_push` works with array by reference// so there's no need to reassign this variablearray_push($_SESSION["shopping_cart"]['product'], $cartArray);$status = 1;

噜噜哒

您的代码看起来不错,但您需要将 session_start() 放在 <?php 标记之后。确保此函数之前没有任何输出(甚至是空格符号等)。所以改变:<?php session_start();到:<?php&nbsp;session_start();
打开App,查看更多内容
随时随地看视频慕课网APP