unserialize() value of database and putting it in json_encode after foreach

╄→гoц情女王★ 提交于 2019-12-02 17:47:20

问题


I insert in database values (array) $row->units with use function serialize()=>[$row->units], how can echo they with unserialize() in json_encode with $row->name? (return send for ajax call in jQuery)

Columns in database:

$row->units => a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}

$row->name=> George Kurdahi

$query = $this->db->query("SELECT * FROM arraha WHERE name LIKE '%$search%' ORDER BY name asc");

$data = array();
foreach ($query->result() as $row)
{
   $data[] = array('name' => $row->name, 'units' => unserialize($row->units)); // Line 22
}
return json_encode($data)

The error for code above is:

A PHP Error was encountered

Severity: Notice

Message: unserialize() [function.unserialize]: Error at offset 277 of 281 bytes

Filename: model.php

Line Number: 22


回答1:


You have some issues with character encoding:

s:15:"Coffee"

15 means length in bytes. So you have to translate encoding of data fetched from DB into encoding that was used with serialize()

You can use json_encode instead of serialize:

$arr = array('Coffee', 'Satellite', /*...*/);
$row->units = json_encode($arr);


来源:https://stackoverflow.com/questions/7269882/unserialize-value-of-database-and-putting-it-in-json-encode-after-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!