PHP 将数组合并为二维 JSON
我有 3 个 JSON 字符串通过 POST 传入,想要将它们合并到一个二维数组中并以 JSON 格式保存到数据库中。 对于这个例子,我有图像 URL、alt 描述和布尔值 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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需字符串连接:
除非您想使用 Json 字符串中的值,否则不需要任何编码/解码。
您可以使用 http://www.jsonlint.com/ 来验证它(删除了 jsonlint 和
print_r
转储以腾出一些空间)Just string concatenate:
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)$url_arr = json_decode('["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"]' );
$alt_arr = json_decode('["测试 int chars àèéìòóù stop","第二个描述",""]'); // 支持UTF-8
$isFav_arr = json_decode('["true", "false", "false"]'); // 字符串需要转换为布尔值
$img_arr = array(
“urls”=>$url_arr,
“alts”=>$alts_arr,
"favs"=>$isFav_arr
);
$结果= json_encode($img_arr);
// 在构建 multidim 数组之前,您可能需要清理数字索引...
$url_arr = json_decode('["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"]');
$alt_arr = json_decode('["testing int chars àèéìòóù stop","second description",""]'); // UTF-8 supported
$isFav_arr = json_decode('["true", "false", "false"]'); // strings need to be converted to booleans
$img_arr = array(
"urls"=>$url_arr,
"alts"=>$alts_arr,
"favs"=>$isFav_arr
);
$results = json_encode($img_arr);
// possibly you will need to clean up numeric indexes ... before building multydim array
简单一点:
保存到数据库取决于您使用的数据库类型。查看使用
mysql_query
或 准备好的语句(首选)。The easy bit:
Saving to the DB depends which DB type you're using. Look at examples using either
mysql_query
, or prepared statements (preferred).