php - 如何在现有的 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函数吗?
解决方案
所以如果它只是一个字符串。然后你可以使用 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
)
)
)
)
推荐阅读
- python - 如何在 Pandas 系列上使用带条件的 loc 函数?
- javascript - 在 React 中是否可以使用钩子来填充从 array.map() 生成的单个输入?
- reactjs - 将 SPA 转换为 SCORM 1.2 包
- node.js - Sequelize nodejs包含模型属性名称别名
- python - Python:在 pandas 中成功结合 str.contains 和 df.groupby
- java - 如何用 Python 为用 Java 编写的 gRPC 服务编写 gRPC 客户端
- git - 恢复特定的 git 提交和依赖于它们的所有后续提交
- mysql - MySQL ERROR 2026 - SSL 连接错误 - Ubuntu 20.04
- mysql - SQL - 从大型数据集中返回多条记录中的最新记录
- php - Laravel 避免子表中的重复条目