user-44651
user-44651

Reputation: 4124

Create a JSON string from PHP array with possible dictionaries

I am trying to build a JSON String similar to this:

{
    "Token": "MyREALLYLongToken",
    "rpc": [
        ["Somthing", "v", "v", ["text", ["s", "123456"]]],
        ["Somthing", "v", "v", ["text", ["i", "6"]]]
    ],
    "MoreText": 7
}

I know that the RPC key value looks like it contains two arrays. But my issues is: how do I create the square bracket members? Are those arrays? Dictionaries? How are those created?

$data = array(
"Token" => "MyREALLYLongToken",
"rpc" => array(
                array(//WHAT HERE?),
                array(//WHAT HERE?)

                ),
"MoreText" => "7"

    );

Upvotes: 2

Views: 2114

Answers (2)

dev87
dev87

Reputation: 164

Try this :

$array = array(
        "token" => "MyREALLYLongToken",
        "rpc" => array(
                        array("somthing", "v", "v", array("text", array("s", "123456"))),
                        array("somthing", "v", "v", array("text", array("i", "6")))
                    ),
        "moretext" => "7"
        );
    echo json_encode($array);

Result is

{"token":"MyREALLYLongToken","rpc":[["somthing","v","v",["text",["s","123456"]]],["somthing","v","v",["text",["i","6"]]]],"moretext":"7"}

Upvotes: 2

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

You need to create arrays within array, like this:

$data = array(
"Token" => "MyREALLYLongToken",
"rpc" => array(
    array("Somthing", "v", "v", array("text", array("s", "123456"))),
    array("Somthing", "v", "v", array("text", array("i", "6")))
    ),
"MoreText" => "7"
);

echo json_encode($data);

Output:

{
    "Token": "MyREALLYLongToken",
    "rpc": [
        ["Somthing", "v", "v", ["text", ["s", "123456"]]],
        ["Somthing", "v", "v", ["text", ["i", "6"]]]
    ],
    "MoreText": "7"
}

Upvotes: 4

Related Questions