如何使用PHP为此对象添加更多字符串? 我已设法生成字符串,但我无法向对象添加更多字符串,也无法删除最后一个逗号。
像这样:
前,
{
"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, );
}
答案 0 :(得分:1)
我想这只是一个字典对象,所以你可以这样做:
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;
答案 1 :(得分:0)
“juan2”,这很有趣。像这样:
$obj->themes[] = (object)array(
"name" => "juan2",
"description" => "esto es un ejemplo2.",
"thumbnail" => "http://example2.com"
);
干杯