Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中如何在JSON中添加属性?_Php_Json - Fatal编程技术网

在PHP中如何在JSON中添加属性?

在PHP中如何在JSON中添加属性?,php,json,Php,Json,我在PHP中使用Json,如下所示: $json = '{"total":"100", "page":"1", "records":"100", "rows": [ {"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}'; $json = '{"total":"100", "page":"1", "records":"100", "rows": [ {"no":"1","part_number":

我在PHP中使用Json,如下所示:

$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
    {"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]}';
我想补充一点

"test1":"5","test2":"7"
在上面的JSON中

所以它将是这样的:

$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';
$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
    {"no":"1","part_number":"2","part_name":"3","price":"4","test1":"5","test2":"7","note":"8"}]}';

请帮帮我。如何在PHP的JSON中添加属性?

您可以使用
JSON\u decode
将JSON字符串解析为数组,将新属性添加到数组中,并使用
JSON\u encode
重新创建JSON字符串。可能重复使用数组定义中的示例。Rio希望添加属性(properties)@user20232359723568423357842364:您只需将
true
作为第二个参数传递给
json\u decode
。没有区别。显然4年前人们不需要这么多的手牵手。初学者总是需要手牵手;)4年前,这里没有那么多{“总数”:“100”,“页面”:“1”,“记录”:“100”,“行”:[{“否”:“1”,“零件编号”:“2”,“零件名称”:“3”,“价格”:“4”,“测试1”:“5”,“测试2”:“7”,“注意”:“8”}],“测试1”:“5”,“测试2”:“7”}这是你的最终输出。与你想要的不匹配它应该是这样的:{“总数”:“100”,“页面”:“1”,“记录”:“100”,“行”:[{“否”:“1”,“零件号”:“2”,“p”‌​艺术名称:““3”,“价格:”:“4”,“测试1:“5”,“测试2:“7”,“注:““8”}]}与此不同:{“总计:”:“100”,“页面:”:“1”,“记录:”:“100”,“行:[{“否:”:“1”,“零件号:”:“2”,“p‌​艺术名称:“3”,“价格”:“4”,“注释”:“8”}],“测试1”:“5”,“测试2”‌​":"7“}是的,谢里夫,这是输出,但与想要的不匹配,你能帮我吗?是的@RioEduardo。我也提到过这个。@user20232359723568423-不,这就是答案,非常感谢你的帮助:)
$json = '{"total":"100", "page":"1", "records":"100", "rows": [ 
{"no":"1","part_number":"2","part_name":"3","price":"4","note":"8"}]}';

// decode json
$json = json_decode($json);

// add data
$json->rows[0]->test1 = "5";
$json->rows[0]->test2 = "7";

// echo it for testing puproses
print_r($json);
// re-encode 
$json = json_encode($json);

echo $json;