PHP将数组合并为2D JSON
问题描述:
我在POST中附带了3个JSON字符串,并希望将它们合并为2维数组并将其以JSON格式保存到数据库中. 对于此示例,我有图像URL,替代说明和boolean isfavorite
I have 3 JSON strings coming in with POST and want to merge these into a 2 dimensional array and save in JSON format to the database. For this example I have image URL's, alt descriptions and booleans isfavorite
$url_arr = json_decode('["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"]');
$alt_arr = json_decode('["testing internat chars àèéìòóù stop","second description",""]'); // UTF-8 supported
$isFav_arr = json_decode('["true", "false", "false"]'); // strings need to be converted to booleans
// merge into 2 dimensional array
// $img_arr = array_merge($url_arr, $alt_arr, $isFav_arr); // doesn't work, just add's to the end
// ...
// save 2D JSON in database
$to_db = json_encode($img_arr);
答
仅字符串连接即可:
$to_db = '['
. '["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"]'
. ',["testing int chars àèéìòóù stop","second description",""]'
. ',["true", "false", "false"]'
. ']';
除非您要使用Json字符串中的值,否则不需要任何编码/解码.
您可以使用 http://www.jsonlint.com/进行验证(删除了jsonlint和print_r
转储以便腾出空间)
Unless you want to work with the values in the Json string, you dont need any en/decoding.
You can use http://www.jsonlint.com/ to validate it (removed jsonlint and print_r
dumps to make some space)