将存储在数据库中的JSON添加到JSON字符串

时间:2015-10-12 13:14:00

标签: php json

我有一些JSON存储在数据库中。请假设我有充分的理由这样做。然后我从数据库中检索它并希望将它包含在另一个JSON字符串中。以下将数据库中的JSON视为标准字符串而不是我想要的JSON。我是否需要循环$json_from_db并首先将cmd值转换为数组/对象,还是有更好的方法?

<?php
$json_from_db=array(
    array('id'=>1,'cmd'=>'{"a":{}}'),
    array('id'=>3,'cmd'=>'{"b":{"name":"x","value":"xxx"}}'),
    array('id'=>5,'cmd'=>'{"b":{"name":"y","value":"yyy"}}'),
    array('id'=>9,'cmd'=>'{"c":{"name":"z","extra":"hello","more"=>1}}'),
);



$arr=array('a'=>"hello",'json'=>array('a'=>"hello"),'json_from_db'=>$json_from_db);
$json=json_encode($arr);
echo($json."\n\n");
print_r(json_decode($json));

输出

{"a":"hello","json":{"a":"hello"},"json_from_db":[{"id":1,"cmd":"\"a\":{}"},{"id":3,"cmd":"\"b\":{\"name\":\"x\",\"value\":\"xxx\"}"},{"id":5,"cmd":"\"b\":{\"name\":\"y\",\"value\":\"yyy\"}"},{"id":9,"cmd":"\"c\":{\"name\":\"z\",\"extra\":\"hello\",\"more\"=>1}"}]}

stdClass Object
(
    [a] => hello
    [json] => stdClass Object
        (
            [a] => hello
        )

    [json_from_db] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [cmd] => "a":{}
                )

            [1] => stdClass Object
                (
                    [id] => 3
                    [cmd] => "b":{"name":"x","value":"xxx"}
                )

            [2] => stdClass Object
                (
                    [id] => 5
                    [cmd] => "b":{"name":"y","value":"yyy"}
                )

            [3] => stdClass Object
                (
                    [id] => 9
                    [cmd] => "c":{"name":"z","extra":"hello","more"=>1}
                )

        )

)

1 个答案:

答案 0 :(得分:1)

请注意,"b":{"name":"x","value":"xxx"}无效json。

您需要解码来自$json_from_db

的所有cmd的json-string
array_walk_recursive($json_from_db, function (&$item, $key) {
    if ($key === 'cmd') {
        $item = json_decode($item, true);
    }
});

然后你可以做

$arr = array(
    'a' => "hello",
    'json' => array('a'=>"hello"),
    'json_from_db' => $json_from_db
);

$json = json_encode($arr);

Demo