PHP 为 json_encode 函数创建值变量

PHP create value variable for json_encode function

我正在使用 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":[{' 部分的 '['

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

您只需要向 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

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]]];