【问题标题】:unserialize() expects parameter 1 to be string, array givenunserialize() 期望参数 1 是字符串,给定数组
【发布时间】:2021-01-13 08:07:03
【问题描述】:

我通过序列化方法将数据存储在mysql表中,现在我想打印所有数据所以我写了mysql查询并尝试反序列化,因为数据是序列化格式但反序列化显示错误。

错误:

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

【问题讨论】:

  • 不确定使用序列化数据是否是数据存储的最佳选择。 JSON 可能是更好的选择。
  • 您的序列化数据在结果集中的一列中,您需要取消序列化,而不是从查询返回的列数组。
  • @NigelRen 之前我存储在 json 中,但是 json 对关联数组来说太糟糕了,我在 stackoverflow 帖子上也确认了这一点
  • 如果您使用select * from table,您将获得某种记录集。即使只有一列一行。然后将该记录集传递给 unserialze,它只需要一个字符串。从相应的行中取出相应的列并将其传递给反序列化。
  • 您从响应中得到一个关联数组。只需像 $var=$result['columnname'] 一样使用 smth,然后使用 $var

标签: php arrays codeigniter serialization


【解决方案1】:

您的$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);
}

【讨论】:

    猜你喜欢
    • 2016-05-17
    • 2015-07-12
    • 2016-04-30
    • 2014-12-09
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多