2011-03-30 104 views
1

我有一个字符串,当我的var_dump返回以下PHP字符串数组

string(20) "{\"key1\":\"key1_value",\"key2\":\"key2_value\"}" 

我如何可以转换成一个数组,将返回以下时,我的var_dump?

array(2) { ["key1"]=> string(20) "key1_value" ["key2"]=> string(20) "key2_value" } 

感谢,
三通

回答

8

它看起来像是一个简单的JSON数组,它受到了PHP的magic_quotes或其他一些转义函数的影响。关闭magic_quotes并在字符串上运行json_decode()

// If you cannot disable `magic_quotes` or you escaped it manually, use this 
$array = json_decode(stripslashes($strings), true); 
+0

谢谢桑德,这工作。我只是在做json_decode而没有使用stripslases这是问题。此外,我实际上需要将其转换为数组,因为您推荐返回StdObject。所以我使用的实际代码是(array)json_decode(stripslashes($ strings)); – teepusink 2011-03-30 19:29:18

+0

其实大卫L.-普拉特建议通过在json_decode中将第二个参数设置为true也起作用。所以json_decode(stripslashes($ strings),true); – teepusink 2011-03-30 19:40:00

+0

啊,是的。当然。我编辑了我的答案供将来参考。 – 2011-03-30 19:59:56

0

explode功能会得到你所需要的。

7

你有什么数据看起来像有效的JSON。你也许可以使用json_decode与第二个参数为true(获得的关联数组)是这样的:

$array = json_decode($string, true); 
0
explode(',\\',$string); 

应该做的伎俩。

+0

我想你的意思是爆炸。 – 2011-03-30 19:20:30

+0

他需要爆炸。 'implode'将数组变成一个字符串。 – 2011-03-30 19:20:36

+0

我已经修好了,谢谢。 ;] – 2011-03-30 20:22:51