TmCrafz
TmCrafz

Reputation: 184

PHP create value variable for json_encode function

I'm using a JSON API; I want to create a variable with values and then convert it to a JSON string via json_encode. The (working) JSON string is this:

$data = '
{
"function":"setArticleImages",
"paras":{
    "user":"'.$user.'",
    "pass":"'.$pass.'",
    "product_model":"'.$productsModel.'",
    "images":{
        "products_id":'.$products_id.',
        "image_name":"'.$imageName.'",
        "image":"'.$image.'",
        "products_images":[{
                "products_id":'.$products_id.',
                "image_name":"'.$imageName2.'",
                "image":"'.$image2.'"
            }        ]
    }
}}
';

I was now trying to write it like this and use json_encode:

$data = array(
    "function" => "setArticleImages",
    "paras" => array(
        "user" => $user,
        "pass" => $pass,
        "product_model" => $productsModel,
        "images" => array(
            "products_id" => $products_id,
            "image_name" => $imageName,
            "image" => $image,
            "products_images" => array(
                "products_id" => $products_id,
                "image_name" => $imageName2,
                "image" => $image2,
            ),
        )
    )
);
$data = json_encode($data);

Unfortunately it does not work. The problems seems to be at '"products_images" => array('. I don't know how to handle the '[' of the '"products_images":[{' part.

Anyone an idea how to write it in the second code snippet?

Upvotes: 0

Views: 639

Answers (2)

Arnaud Brenier
Arnaud Brenier

Reputation: 117

The "{ }" in th JSON notation is a PHP array with alphanumerical key.

So :

$array = ["foo" => [1,2,3], "bar" => [4,5,6]

will be converted in a JSON string :

{ foo : [1,2,3], bar: [4,5,6]}

So if you are looking to a JSON that looks like this

[{ foo : [1,2,3], bar: [4,5,6]}]

You will have to do an array with numeric keys that contains your alphanumerical array :

$array = [["foo" => [1,2,3], "bar" => [4,5,6]]];
// same as
$array = [ 0 => ["foo" => [1,2,3], "bar" => [4,5,6]]];

Upvotes: 0

Nick
Nick

Reputation: 147166

You just need to add an extra level of array to the products_images element, so that you get a numerically indexed array of associative arrays, giving you the array of objects form you want:

$data = array(
    "function" => "setArticleImages",
    "paras" => array(
        "user" => $user,
        "pass" => $pass,
        "product_model" => $productsModel,
        "images" => array(
            "products_id" => $products_id,
            "image_name" => $imageName,
            "image" => $image,
            "products_images" => array(
                array(
                    "products_id" => $products_id,
                    "image_name" => $imageName2,
                    "image" => $image2,
                )
            ),
        )
    )
);

Demo on 3v4l.org

Upvotes: 3

Related Questions