简体   繁体   English

如何在PHP中将JSON数组的字符串转换为对象数组

[英]How to convert string of JSON array to array of object in PHP

suppose I have 假设我有

$obj = "[{'A':'a1','B':2,'C':'c1'},{'A':'a2','B':2,'C':'c2'}]"

And I want to convert it to array of object. 我想将它转换为对象数组。

obj[0](
A => 'a1'
B => 2
C => 'c1'
)

How can I do? 我能怎么做?

Use str_replace() to change single quotes to double quote for proper json string. 使用str_replace()将单引号更改为适当的json字符串的双引号。

Then use json_decode() to convert it into array. 然后使用json_decode()将其转换为数组。

$obj = "[{'A':'a1','B':2,'C':'c1'},{'A':'a2','B':2,'C':'c2'}]";
$newobj = str_replace("'", '"', $obj);
$arr = json_decode($newobj);
print_r($arr);

Output 产量

Array
(
    [0] => stdClass Object
        (
            [A] => a1
            [B] => 2
            [C] => c1
        )

    [1] => stdClass Object
        (
            [A] => a2
            [B] => 2
            [C] => c2
        )

)

Check Demo : Click Here 检查演示: 点击这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM