PHP将数组合并为2D JSON [英] PHP merge arrays into 2D JSON

查看:166
本文介绍了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)

这篇关于PHP将数组合并为2D JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆