如何从已保存的数据循环为购物车格式?

How can I loop from a saved data as cart format?

我已经在 Opencart 网站上工作了几天。老开发者在旧的 table 中保存了一些数据,其中有一列名为 cart。在本专栏中,我获得了允许我(我猜)显示已订购的产品、数量和价格的数据。我需要制作一个 foreach() 循环并显示此信息。我该怎么做 ?一个保存数据的例子:a:3:{i:144;s:1:"2";i:172;i:2;i:193;i:1;}

这叫做 serialized array. At the most basic level, you can unserialize() 它并像这样遍历购物车数据:

$cart = unserialize('a:3:{i:144;s:1:"2";i:172;i:2;i:193;i:1;}');
foreach ($cart as $product_id => $quantity) {
    echo "Product ID: $product_id\n";
    echo "Quantity: $quantity\n\n";
}

输出:

Product ID: 144
Quantity: 2

Product ID: 172
Quantity: 2

Product ID: 193
Quantity: 1

如果涉及选项,事情会变得更加复杂,与其复制购物车库函数,不如直接使用 Opencart 的核心恢复购物车并迭代产品:

// query the database
$query = $this->db->query("SELECT cart FROM " . DB_PREFIX . "table_name WHERE customer_id = '123'")->row;

// unserialize the resulting row
$cart = unserialize($query['cart']);

// initialize the session array
$this->session->data['cart'] = array();

// restore cart to session
foreach ($cart as $key => $value) {
    $this->session->data['cart'][$key] = $value;
}

// loop through products
foreach ($this->cart->getProducts() as $product) {
    print_r($product);
}