PHP为json_encode函数创建值变量

时间:2019-04-16 12:20:31

标签: php json encode

我正在使用JSON API;我想创建一个带值的变量,然后通过json_encode将其转换为JSON字符串。 (有效的)JSON字符串是这样的:

$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.'"
            }        ]
    }
}}
';

我现在正试图这样写,并使用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);

不幸的是,它不起作用。问题似乎出在'"products_images" => array('。我不知道如何处理'['部分的'"products_images":[{'

有人知道如何在第二个代码段中编写它吗?

2 个答案:

答案 0 :(得分:3)

您只需要向products_images元素添加一个额外级别的数组,即可获得一个关联数组的数字索引数组,从而为您提供所需的对象数组:

$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

答案 1 :(得分:0)

JSON表示法中的“ {}”是带有字母数字键的PHP数组。

所以:

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

将转换为JSON字符串:

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

因此,如果您要查找的是这样的JSON

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

您将不得不使用包含您的字母数字数组的数字键来做一个数组:

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