如何在json对象内添加数组[关闭]

问题描述 投票:0回答:2

我想将数组追加到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"
        }
    ]
]
php arrays json
2个回答
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)

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

有帮助吗?

© www.soinside.com 2019 - 2024. All rights reserved.