首页 > 解决方案 > 如何在现有的 JSON 数组中推送单个元素?

问题描述

我有一个数组,我想在其中添加一个 json 元素。这是数组。

"six": {
            "donnes_table_two": [
                {
                    "denomination_de_vente": "value",
                    "marques": "value"
                },
                {
                    "denomination_de_vente": "value",
                    "marques": "value"
                }
            ]
        }

我想在添加它看起来的 id 之后在每个数组元素中添加 ID。

"six": {
            "donnes_table_two": [
                {   "id" : "1",
                    "denomination_de_vente": "value",
                    "marques": "value"
                },
                {  
                    "id" = "1",
                    "denomination_de_vente": "value",
                    "marques": "value"
                }
            ]
        }

每个元素的 ID 都相同。我可以不使用循环吗?有什么PHP函数吗?

标签: phparraysjson

解决方案


所以如果它只是一个字符串。然后你可以使用 PHP在之前str_replace添加,如下例所示"id":"1""denomination_de_vente"

<?php
$json = '{"six":{
            "donnes_table_two": [
                {
                    "denomination_de_vente": "value",
                    "marques": "value"
                },
                {
                    "denomination_de_vente": "value",
                    "marques": "value"
                }
            ]
        }}';

//$json = json_encode($yourObject);//if it is an php object or Array
$json = str_replace('"denomination_de_vente"','"id":"1","denomination_de_vente"',$json);
print_r(json_decode($json,true));// here 'true' to get result as array in your case
?>

现场演示

输出

Array
(
    [six] => Array
        (
            [donnes_table_two] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [denomination_de_vente] => value
                            [marques] => value
                        )

                    [1] => Array
                        (
                            [id] => 1
                            [denomination_de_vente] => value
                            [marques] => value
                        )

                )

        )

)

推荐阅读