[英]How to insert a new key value to the existing JSON- PHP
I have been searching online for the past 2 hours and couldn't find an answer.过去2小时我一直在网上搜索,但找不到答案。 I have some data stored in my database in JSON format.
我有一些数据以 JSON 格式存储在我的数据库中。 I want to add a new key and value to the json data.
我想向 json 数据添加一个新的键和值。 Example
例子
{
"systemService":"1234",
"DATA_PLAN":"SMEF",
"amount":"5000"
}
$message = .$name "" .$post;
I want to add a new key and value to it.我想为它添加一个新的键和值。
"message":$message
to something like this.到这样的事情。
{
"systemService":"1234",
"DATA_PLAN":"SMEF",
"amount":"5000"
"message":"mike accountance"
}
How do I go about it in PHP我如何在 PHP 关于它的 go
Here is an example how you can do it:这是一个示例,您可以这样做:
Method 1 decoding it to an associative array:方法1将其解码为关联数组:
$object = json_decode('{
"systemService":"1234",
"DATA_PLAN":"SMEF",
"amount":"5000"
}', true);
$object['message'] = "Your message";
echo json_encode($object); //this will give you the json string with your new property
Method 2 decoding it to an object:方法 2 将其解码为 object:
$object = json_decode('{
"systemService":"1234",
"DATA_PLAN":"SMEF",
"amount":"5000"
}');
$object->message = "Your message";
echo json_encode($object); //this will give you the json string with your new property
You could convert the JSON string to object (with PHP json_decode
function), add the new property, then convert it back to string (with PHP json_encode
function), ie : You could convert the JSON string to object (with PHP
json_decode
function), add the new property, then convert it back to string (with PHP json_encode
function), ie :
$str = '{
"systemService": "1234",
"DATA_PLAN": "SMEF",
"amount": "5000"
}';
$obj = json_decode($str);
$obj->message = 'mike accountance';
$str = json_encode($obj);
echo $str;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.