Home  >  Article  >  Backend Development  >  PHP如何将这样的字符串变成数组

PHP如何将这样的字符串变成数组

WBOY
WBOYOriginal
2016-06-23 14:22:46877browse

本帖最后由 tangl198710 于 2011-08-12 12:11:55 编辑

字符串如下:

{'aid':'21','ctl_a_cpu':'df','ctl_a_ram':'df','ctl_a_disk':'df','ctl_a_fip':'df','ctl_a_os':'c_1_2','ctl_a_os_lang':'c_4_1,c_4_3','comment':'其它要求\',\'呵呵\',\'','total':'1090','typeid':'6'}

这样的字符串怎么转换成数组使用了?

如上的字符串转换成数组  :号前的为下标 后面的是值   要怎么处理呢,望高手指点

回复讨论(解决方案)

$str = <<<EOF{'aid':'21','ctl_a_cpu':'df','ctl_a_ram':'df','ctl_a_disk':'df','ctl_a_fip':'df','ctl_a_os':'c_1_2','ctl_a_os_lang':'c_4_1,c_4_3','comment':'其它要求\',\'呵呵\',\'','total':'1090','typeid':'6'}EOF;$ar = json_decode($str, true);print_r($ar);

json_decode 使用这个函数有什么特别注意的东西没? 我打印出来是空白,已找到其它方法解决了。但想知道 json_decode 这个函数怎么使用的

楼主,你那个格式不正确
不知道你用什么工具输出的json数据啊

楼主来看看这个例子

$str1 ='{"a":21}';
$str2="{\"b\":21}";
$str3="{'c':21}";
print_r(json_decode($str1,true));
print_r(json_decode($str2,true));
print_r(json_decode($str3,true));


 输出结果为Array ( [a] => 21 ) Array ( [b] => 21 ) 

第三个print_r输出为空白

json_decode ( string $json [, bool $assoc ] )
接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 

参数
json 
待解码的 json string 格式的字符串。 

assoc 
当该参数为 TRUE 时,将返回 array 而非 object 。 


同上,直接json_decode这个字符串。
这样写:
json_decode($str, true);
注意如果不加“true”的话,转化成的是对象,加了true以后才是数组

恩。。果然无法直接用json_decode()处理,改手工方式转换:

$str = <<<EOF{'aid':'21','ctl_a_cpu':'df','ctl_a_ram':'df','ctl_a_disk':'df','ctl_a_fip':'df','ctl_a_os':'c_1_2','ctl_a_os_lang':'c_4_1,c_4_3','comment':'其它要求\',\'呵呵\',\'','total':'1090','typeid':'6'}EOF;$ar = explode("','", substr($str, 2, -2));$result = '';foreach($ar as $v) {   $ar_tmp = explode("':'", $v);   $result[$ar_tmp[0]] = $ar_tmp[1];}echo '<pre class="brush:php;toolbar:false">';print_r($result);


PHP数组基础
http://3aj.cn/php/39.html

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn