unserialize() value of database and putting it in

2019-03-04 05:24发布

问题:

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