我用serialize方法将数据存储在mysql表中,现在我想打印所有数据。所以我写了mysql查询并试图取消序列化,因为数据是serialize格式,但取消序列化显示错误。
错误:
unserialize() expects parameter 1 to be string, array given
查询以获取所有记录
$this->db->select('*');
$this->db->from($table);
$result=$this->db->get()->result();
$unserialize_list=unserialize($result);
您的$result
变量包含一个多维数组。
假设表中的一些数据是序列化的,并且由于您还没有发布表模式,下面是一个示例表,我希望它与您的用例相匹配:
Id | Data
-------------------
1 | a:2:{s:4:"Name";s:5:"Test1";s:8:"Location";s:9:"Somewhere";}
2 | a:2:{s:4:"Name";s:5:"Test2";s:8:"Location";s:14:"Somewhere Else";}
3 | a:2:{s:4:"Name";s:5:"Test3";s:8:"Location";s:18:"Somewhere Else Too";}
运行此代码:
$this->db->select('*');
$this->db->from($table);
$result=$this->db->get()->result();
$unserialize_list=unserialize($result);
将产生一个对象数组,表中每行一个,如下所示:
Array
(
[0] => stdClass Object
(
[Id] => 1
[Data] => a:2:{s:4:"Name";s:5:"Test1";s:8:"Location";s:9:"Somewhere";}
)
[1] => stdClass Object
(
[Id] => 2
[Data] => a:2:{s:4:"Name";s:5:"Test2";s:8:"Location";s:14:"Somewhere Else";}
)
[2] => stdClass Object
(
[Id] => 2
[Data] => a:2:{s:4:"Name";s:5:"Test3";s:8:"Location";s:18:"Somewhere Else Too";}
)
)
您需要运行以下代码才能访问未序列化的数据:
foreach ($result as $line) {
$unserializedData = unserialize($line->Data);
// Use the unserialized data as needed...
print_r($unserializedData);
}