0

I have some JSON stored in a database. Please assume I have a good reason for doing so. I then retrieved it from the DB and wish to include it in another JSON string. The following treats the JSON from the DB as standard strings instead of JSON as I desire. Will I need to loop over $json_from_db and first convert the cmd values to arrays/objects, or is there a better way?

<?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));

OUTPUT

{"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
  • Please assume I have a good reason for doing so you know you doing something wrong! Commented Oct 12, 2015 at 13:24

1 Answer 1

1

Note that "b":{"name":"x","value":"xxx"} isn't valid json.

You need to decode all cmd's json-string from $json_from_db,

array_walk_recursive($json_from_db, function (&$item, $key) {
    if ($key === 'cmd') {
        $item = json_decode($item, true);
    }
});

Then you can do

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

$json = json_encode($arr);

Demo.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Federico, Yea, I just realized my JSON was messed up. Let me check out your code. Thanks!
Nice use of array_walk_recursive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.