2010-11-02 63 views
1

我有3个JSON字符串与POST进来,并希望将它们合并到一个2维数组中,并以JSON格式保存到数据库中。 对于这个例子,我有图片的URL,ALT描述和布尔isfavoritePHP将数组合并到2D JSON中

$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); 
+0

你想要的三个阵列是在阵列之前清理数字索引......吧?并且你想将JSON保存在数据库中,对吗? – Gordon 2010-11-02 14:08:27

+0

是的,没错。 – FFish 2010-11-02 14:09:56

回答

1

只是字符串串连:

$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_rdumps,使一些空间

+0

mmm,是的,我认为是这样..是这个有​​效的JSON?我的意思是我可以json_decode()我需要能够访问例如'alt for second image'等。 – FFish 2010-11-02 14:15:23

+0

我刚刚尝试echo print_r(json_decode($ to_db));但它返回1?难道这不是更好的[[“001.jpg”,“descr 1”,false],[“002.jpg”,“descr 2”,true]] – FFish 2010-11-02 14:22:22

+0

@FFish我不知道我明白你是什么问。它是有效的(在我添加了缺失的逗号之后),并且如果您想将Json字符串推送到数据库,那么这应该是首选的方式,因为解码它是昂贵的。 – Gordon 2010-11-02 14:24:08

0

最简单的一点:

$img_arr = array(); 

for ($i=0; $i < sizeof($url_arr); $i++) { 
    $img_arr[] = array($url_arr[$i], $alt_arr[$i], $isFav_arr[$i]); 
} 

保存到数据库取决于你使用的数据库类型。查看使用mysql_queryprepared statements(首选)的示例。

+0

谢谢你,简单比我容易... – FFish 2010-11-02 14:10:57

+0

逃跑如果你看到一个for循环sizeof!预先计算好的长阵列长度 – nerkn 2010-11-02 14:39:18

1

$ 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”,“second description”,“”]'); // UTF-8支持 $ isFav_arr = json_decode('[“true”,“false”,“false”]'); //串需要转换到布尔值

$ img_arr =阵列( “网址”=> $ url_arr, “ALTS”=> $ alts_arr, “的收藏”=> $ isFav_arr
); $ results = json_encode($ img_arr);

//可能你需要构建multydim阵列

+0

这也是一个很好的答案,但戈登的解决方案保存了json编码,就像我的例子中我已经编码了它们一样。干杯 – FFish 2010-11-02 17:05:31