反序列化PHP字符串

时间:2018-06-21 21:41:35

标签: php arrays

我有一个从我的函数之一返回的序列化字符串:

a:1:{i:0;a:3:{s:2:"id";s:24:"xxxxxxxxxxxxxxxxxxxxxxxx";s:11:"description";s:3:"Two";s:9:"users-idt";s:36:"x6543rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrd";}}

但是当我对此使用unserialize()时,它不会返回数组

<?php
 $arr = unserialize($string); //returns empty

1 个答案:

答案 0 :(得分:1)

您的-最初发布的-序列化的字符串无效,请参见计算len给出的字符串,得出正确的结果:

<?php
$original = 'a:1:{i:0;a:3:{s:2:"id";s:24:"xxid";s:11:"description";s:3:"Two";s:9:"user-id";s:36:"x6543rd";}}';
                                     ||                                       ||            ||
                                     \/                                       \/            \/  
$edited   = 'a:1:{i:0;a:3:{s:2:"id";s:4:"xxid";s:11:"description";s:3:"Two";s:7:"user-id";s:7:"x6543rd";}}';

$arr = unserialize($edited);

echo '<pre>';
var_dump($arr);
echo '</pre>';
?>

//output
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    string(4) "xxid"
    ["description"]=>
    string(3) "Two"
    ["user-id"]=>
    string(7) "x6543rd"
  }
}

您的-已编辑-字符串可以正常工作,使用上面的代码运行它,输出:

array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    string(24) "xxxxxxxxxxxxxxxxxxxxxxxx"
    ["description"]=>
    string(3) "Two"
    ["users-idt"]=>
    string(36) "x6543rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrd"
  }
}