所以我正在处理客户购物篮。我发现适合我的目的的最佳方法是将对象(为每个项目属性设置属性)存储在一个数组中。所以我最终得到了一个 ItemObject 类型的对象数组。
我阅读了将这个对象数组存储在 MySQL 表中的最佳方法,即对其进行序列化,从而将其转换为字符串然后存储。然后当我需要它时,我可以使用 php 函数 unserialize() 它。
我就是这样做的……现在我反序列化它,我收到一个错误……下面是 ItemObject 和反序列化部分的代码。如何将该字符串反序列化回 ItemObjects 类型的对象数组,以便可以迭代并打印出每个项目的详细信息?
<?php
$dateSelected = $_GET['date'];
echo "Date: ".$dateSelected . "<br>";
mysql_connect();
mysql_select_db("dashjkd");
$result = mysql_query("SELECT order_object FROM orders WHERE orderDate = '".$dateSelected."'");
if(mysql_num_rows($result) > 0){
$temp;
while($row = mysql_fetch_assoc($result)){
$temp = $row['order_object'];
//print_r($temp);
}
echo "Array: <br>";
$basketObjArray = array();
$basketObjArray = unserialize($temp);
print_r($basketObjArray);
foreach($basketObjArray as $key => $value)
{
echo "Key: " . $key;
echo "Value: ". $value;
}
}else{
echo "Something went horribly wrong..try again!";
}
?>
而这个反序列化代码会导致这个错误和奇怪的输出:
Date: 2012-04-18
Array:
Array ( [0] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => ItemObject [itemNameVar] => whitethoab [itemQtyVar] => 12 [itemPriceVar] => 10 ) [1] => stdClass Object ( [itemNameVar] => woolthoab [itemPriceVar] => 10 [itemQtyVar] => 2 ) [2] => stdClass Object ( [itemNameVar] => shemag [itemPriceVar] => 4 [itemQtyVar] => 1 ) [3] => stdClass Object ( [itemNameVar] => jacket [itemPriceVar] => 12 [itemQtyVar] => 2 ) ) Key: 0
Catchable fatal error: Object of class __PHP_Incomplete_Class could not be converted to string in /home/sdsds/public_html/laundry/customerorder.php on line 21
我设计的 itemObject 非常简单,并且在我尝试在序列化之前显示数组之前工作过:
class ItemObject{
public $itemNameVar;
public $itemQtyVar;
public $itemPriceVar;
}
谢谢您的帮助 :)