使用PHP在对象中添加更多字符串
如何使用PHP向该对象添加更多字符串? 我已经成功地生成了字符串,但是我不能向对象添加更多的字符串,也不能删除最后一个逗号 像这样: 以前,使用PHP在对象中添加更多字符串,php,json,Php,Json,如何使用PHP向该对象添加更多字符串? 我已经成功地生成了字符串,但是我不能向对象添加更多的字符串,也不能删除最后一个逗号 像这样: 以前, { "themes":[ { "name": "Amelia", "description": "Sweet and cheery.", "thumbnail": "http://bootswatch.com/amelia/thumbnail.png" } ] } 之
{
"themes":[
{
"name": "Amelia",
"description": "Sweet and cheery.",
"thumbnail": "http://bootswatch.com/amelia/thumbnail.png"
}
]
}
之后,
{
"themes":[
{
"name": "juan",
"description": "esto es un ejemplo.",
"thumbnail": "http://example.com"
},
{
"name": "juan2",
"description": "esto es un ejemplo2.",
"thumbnail": "http://example2.com"
},
]
}
更新代码:
// $_POST = Request::post
if (Request::post('theme_title')) $theme_title = Request::post('theme_title'); else $theme_title = '';
if (Request::post('theme_img')) $theme_img = Request::post('theme_img'); else $theme_img = '';
if (Request::post('theme_desc')) $theme_desc = Request::post('theme_desc'); else $theme_desc = '';
$jsonfile = 'events.json';
$data->themes[] = (object)array(
"name" => $theme_title,
"description" => $theme_img,
"thumbnail" => $theme_desc
);
$json = str_replace('\/','/',json_encode( $data ));
// $_POST = Request::post
if (Request::post('Themes_add')){
// file_put_contents
File::setContent( $jsonfile, $json,$create_file = true, $append = true, );
}
我想这只是一个dictionary对象,因此您可以执行以下操作:
obj["key1"] = [];
obj["key2"] = [];
{
"themes":[
{
"name": "juan",
"description": "esto es un ejemplo.",
"thumbnail": "http://example.com"
},
{
"name": "juan2",
"description": "esto es un ejemplo2.",
"thumbnail": "http://example2.com"
},
],
"key1":[],
"key2":[]
}
或者,要将另一个存储在$person中的对象添加到主题键,您可以:
obj["themes"][] = $person;
“juan2”,真有趣。大概是这样的:
$obj->themes[] = (object)array(
"name" => "juan2",
"description" => "esto es un ejemplo2.",
"thumbnail" => "http://example2.com"
);
干杯,嗯?要么你不懂这个问题,要么我不懂我可能不明白这个问题。我以为他想给某个dictionary对象添加另一个键。但是看看这个例子,我认为你是对的,他想把它添加到主题列表中。谢谢,但这只是生成了没有添加的内容。那么,你又做错了什么。这里,
$obj
是您的顶级对象。只要这是正确的,这将向对象的主题
数组中添加新条目。此外,如果您希望人们继续帮助您,请确保向上投票您认为有用的答案。