如何在json对象中添加数组

时间:2019-12-26 08:46:07

标签: php arrays json

我想将数组追加到json对象/数组,即追加到{'text','Row 1 column 2'

我有一个像这样的JSON数组:

[
    [
        {
            "text":"Row 1 Column 1"
        }
    ],
    [
        {
            "text":"Row 2 Column 1"
        },
        {
            "text":"Row 2 Column 2"
        }
    ]
]

预期结果如下:

[
    [
        {
            "text":"Row 1 Column 1"
        },
        {
            "text":"Row 1 Column 2"
        }
    ],
    [
        {
            "text":"Row 2 Column 1"
        },
        {
            "text":"Row 2 Column 2"
        }
    ]
]

2 个答案:

答案 0 :(得分:3)

$json= '
    [
        [
            {
                "text":"Row 1 Column 1"
            }
        ],
        [
            {
                "text":"Row 2 Column 1"
            },
            {
                "text":"Row 2 Column 2"
            }
        ]
    ]
    ';

    $p = json_decode($j);

    $p[0][]=["text"=>"Row 1 Column 2"];

    print_r(json_encode($p)); // print_r for debug, $result = json_encode($p)

答案 1 :(得分:0)

您需要先处理数组中的数据,然后将其转换为json数组

我会这样:

$array = [
    [
        [
            "text" => "Row 1 Column 1"
        ]
    ],
    [
        [
            "text" => "Row 2 Column 1"
        ],
        [
            "text" => "Row 2 Column 2"
        ]
    ]
];

// a element in the first sub array
$array[0][] = [
    "text" => "Row 1 Column 2"
];

有帮助吗?