2015-11-08 23 views
1

我一直在Opencart網站上工作幾天。舊開發人員在一箇舊表中保存了一些數據,其中有一列名爲cart。在本專欄中,我有數據可以讓我(我猜)顯示訂購的產品,數量和價格。我需要製作一個foreach()循環並顯示此信息。我該怎麼做 ?保存數據的一個示例:a:3:{i:144;s:1:"2";i:172;i:2;i:193;i:1;}如何從保存的購物車格式中循環播放?

回答

0

這就是所謂的serialized array。在最基本的層面上,你可以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"; 
} 

OUTPUT:

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); 
}