2013-03-12 78 views
0

我正在使用wordpress with nextgen gallery,並且我想要從獨立的JSON文件中的特定庫ID中獲取圖像。到目前爲止,我有這個代碼,但只是從給定的ID(在這種情況下; 7)導出圖像。我知道必須有某種foreach函數,但我的JavaScript知識不會那麼遠。導出多個json文件

有人可以幫我這個嗎?我的代碼至今:

mysql_connect("localhost","DB-NAME","DB-PASSWORD"); 
mysql_select_db("DB-NAME"); 

$result=mysql_query("SELECT filename FROM zs_ngg_pictures WHERE galleryid = '7' ORDER BY sortorder LIMIT 3"); 

while($row=mysql_fetch_assoc($result)){ 
$output[]=$row; 
} 

$fp = fopen('result.json', 'w'); 
fwrite($fp, json_encode($output)); 
fclose($fp); 

echo json_encode($output); 

回答

0

如果我理解正確,你想實現你可以簡單地讓所有的圖片是什麼,把它們放在一個多維數組:

$result=mysql_query("SELECT filename, galleryid FROM zs_ngg_pictures ORDER BY sortorder"); 

while($row=mysql_fetch_assoc($result)){ 
    $output[$row['galleryid']][] = $row['filename']; 
} 

,你有PHP數組像這樣(如果你有兩個畫廊id爲7和23):

array(
    7 => array('file7-1.jpg','file7-2.jpg','file7-3.jpg'), 
    23 => array('file23-1.jpg','file23-2.jpg'), 
); 

所以result.json文件會像:

{ "7" : ["file7-1.jpg", "file7-2.jpg", "file7-3.jpg"], 
    "23" : ["file23-1.jpg", "file23-2.jpg"] } 

如果你想爲每個galleryid那麼你就可以循環並保存不同名稱的文件單獨的文件:

foreach($output as $gall_id => $gallery) { 
    file_put_contents('result-'.$gall_id.'.json', json_encode($gallery)); 
} 

,你就會有一個名爲result-7.json兩個文件,並result-23.json

+0

謝謝Guglie是底部正是我所需要的東西。我現在爲每個ID獲取一個獨特的json文件。再次感謝! – Koen 2013-03-13 16:08:34

+0

歡迎您參觀@ powtac的建議。 – Guglie 2013-03-13 16:18:07

+0

我也看到了這一點。沒有測試它,但由它的輸出看起來只輸出一個json文件... – Koen 2013-03-13 17:59:39

0

相反做複雜的東西fopen()東西和echo

$fp = fopen('result.json', 'w'); 
fwrite($fp, json_encode($output)); 
fclose($fp); 

echo json_encode($output); 

,你可以簡單地調用:

file_put_contents('result.json', json_encode($output)); 
readfile('result.json'); 

或跳過的文件和簡單的輸出JSON:

echo json_encode($output));