如何解析WordPress选项json

时间:2016-01-30 作者:Sachin Stellen

我使用以下格式的插件保存数据:

a:7:{s:6:\'Sunday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'13: 00 \';}
    s:6:\'Monday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\' end \';s:5:\'17: 00 \';}
    s:7:\'Tuesday \';a:3:{s:6:\' active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'17: 00 \';}
    s:9:\'Wednesday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'17: 00 \';}
    s:8:\'Thursday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'17: 00 \';}
    s:6:\'Friday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'17: 00 \';}
    s:8:\'Saturday \';a:3:{s:6:\'active \';s:3:\'yes \';s:5:\'start \';s:5:\'08: 00 \';s:3:\'end \';s:5:\'13: 00 \';}}
如何使用php或任何WordPress函数提取这些数据?我已经试过了unserialize(), maybe_unserialize() json_decode . 但最终我得到的都是空的。

1 个回复
最合适的回答,由SO网友:Howdy_McGee 整理而成

注释和答案是正确的,它不是JSON,而是serialized array. 无法取消序列化的原因是序列化数据中有引号。David Walsh wrote a neat article about this. 问题是,您不能简单地进入数据库并删除这些单引号,因为序列化的值跟踪字符串中的字符数(s:6) 所以你也需要更新它。

以下是David Walsh建议在未来绕过此问题的内容:

//to safely serialize
$safe_string_to_store = base64_encode( serialize( $multidimensional_array ) );

//to unserialize...
$array_restored_from_db = unserialize( base64_decode( $encoded_serialized_string ) );