与CakePHP 2的购物车

时间:2016-09-01 09:01:30

标签: php cakephp

我正在尝试使用Cookie中的数组与CakePHP 2进行某种购物车。

我做了什么:

public $components = array('Cookie');

public function beforeFilter(){
    $this->Cookie->name= ' order_cookie';
}

按钮调用此功能:

public function addOrder(){
    $this->Cookie->write('order_cookie', array(
        'order_id' => $order_id,
        'quantity' => $this->request->data['addOrder']['quantity'],
        'description' => $this->request->data['addOrder']['description'],
        'price' => $this->request->data['addOrder']['price']
    ));
}

我在视图order.ctp中显示结果。这是order控制器:

public function order(){
    $this->set('myorder', $this->Cookie->read('order_cookie'));
}

在视图中order.ctp

<table>             
    <thead>
        <tr>
            <th>Order ID</th>
            <th>Quantity</th>
            <th>Description</th>
            <th>Price</th>
        </tr> 
    </thead>

    <tbody>
    <?php
    if(isset($myorder)){
        foreach($myorder as $theorder){
            ?>            
            <tr>
                <td><?php echo $theorder['order_id'];?></td>
                <td><?php echo $theorder['quantity'];?></td>
                <td><?php echo $theorder['description'];?></td>
                <td><?php echo $theorder['price'];?></td>
            </tr>
        </tbody>
        <?php
        }
    }
    ?>
</table>

我有两个问题:

  1. 当我添加订单时,它会删除之前的订单而不是添加新订单

  2. 当我显示结果时,它会在每行和每行中为我提供Warning : Illegal string offset

  3. 我想要的是什么:

    我只是希望当客户添加订单时,程序会在cookie中添加数组而不是删除之前的数据,最后会正确显示结果。

1 个答案:

答案 0 :(得分:1)

您的问题是如何写入您的Cookie。 addOrder函数中的此方法调用每次调用时都会覆盖您的数据: -

$this->Cookie->write('order_cookie', array(
    'order_id' => $order_id,
    'quantity' => $this->request->data['addOrder']['quantity'],
    'description' => $this->request->data['addOrder']['description'],
    'price' => $this->request->data['addOrder']['price']
));

您要做的是将新数据附加到order_cookie。您需要先读取cookie数据,然后在重新编写cookie之前附加到该数据。例如: -

$orderCookie = $this->Cookie->read('order_cookie');

$orderCookie[] = array(
    'order_id' => $order_id,
    'quantity' => $this->request->data['addOrder']['quantity'],
    'description' => $this->request->data['addOrder']['description'],
    'price' => $this->request->data['addOrder']['price']
);

$orderCookie = $this->Cookie->write('order_cookie', $orderCookie);

order_cookie现在将是一个数字索引的订单详细信息数组。