如何将字符串转换为对象数组

时间:2018-10-29 11:39:23

标签: php codeigniter

我有这种字符串。

[
    {
        "uniqueID" : "com.product",
        "name" : "john doe",
        "price" : "15",
        "description" : "some description"
    },
    {
        "uniqueID" : "com.product1",
        "name" : "john doe",
        "price" : "15",
        "description" : "some descriptio"
    }
]

,我想将其更改为对象数组。喜欢

Array
(
 [0] => [
    {
        "uniqueID" : "com.product",
        "name" : "john doe",
        "price" : "15",
        "description" : "some descriptio"
    },

    [1] => 
    {
        "uniqueID" : "com.product1",
        "name" : "john doe",
        "price" : "15",
        "description" : "some description"
    },
]
)

我怎么做到的,我用了这段代码

  $data = $this->input->post('productArray');
  $dataArray = explode('},' , $data);

但是它给了我这种解决方案。这不是我的要求。

Array
(
    [0] => [
    {
        "uniqueID" : "com.product",
        "name" : "john doe",
        "price" : "15",
        "description" : "some description"

    [1] => 
    {
        "uniqueID" : "com.product1",
        "name" : "john doe",
        "price" : "15",
        "description" : "some description"
    }
]
)

如果您能帮助我,这将是我的荣幸。

1 个答案:

答案 0 :(得分:1)

json_decode是您要寻找的东西。它是内置的PHP函数。这是下面列出的示例代码,使用您的json字符串作为输入:

$string = '[{"uniqueID":"com.product","name":"john doe","price":"15","description":"some description"},{"uniqueID":"com.product1","name":"john doe","price":"15","description":"some descriptio"}]';

$array = json_decode($string);

print_r($array);

//输出///

  

Array([0] => stdClassObject([uniqueID] => com.product [名称   ] => johndoe [价格] => 15 [描述] => somedescription)[1   ] => stdClassObject([uniqueID] => com.product1 [name] => johndoe [
  价格] => 15 [描述] => somedescriptio))