2011-06-02 35 views
8

基於以下答案更新:有道用PHP創建JSON數據/ MySQL的

基於下面的答案,我現在有以下PHP腳本:

header('Content-type:application/json'); 

function getdata($the_query) 
{ 
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error()); 
    $db = mysql_select_db('db_name', $connection) or die (mysql_error()); 

    $results = mysql_query($the_query) or die(mysql_error()); 

    header('Content-type:application/json'); 

    $the_data['rss']['channels']['title'] = $title; 
    $the_data['rss']['channels']['link'] = $link; 
    $the_data['rss']['channels']['description'] = $description; 

    while($row = mysql_fetch_array($result)) 
    { 
     extract($row); 

     $the_data['rss']['channels']['items']['title'] = $item_title; 
     $the_data['rss']['channels']['items']['link'] = "$item_link; 
     $the_data['rss']['channels']['items']['date'] = $item_date; 
     $the_data['rss']['channels']['items']['description'] = $item_description; 
    } 

    mysql_close($connection); 

    return json_encode($the_data); 
} 

它返回以下:

{ 
    "rss": 
    { 
     "channels": 
     { 
      "title":"title goes here", 
      "link":"link goes here", 
      "description":"description goes here", 
      "items": 
      { 
       "title":"'title goes here", 
       "link":"link goes here", 
       "date":"date goes here", 
       "description":"description goes here" 
      } 
     } 
    } 
} 

它應該基於從數據庫返回的行數返回很多項目,爲什麼我只獲得1個項目?

+4

您從MySQL獲取數據到一個數組中,然後運行'json_encode($ your_array)'就完成了。 – 2011-06-02 10:03:10

+1

你的輸出將不會工作順便說一句。你有幾個'item'元素。我假定這個JSON被解析時,只有最後一個會「生存」。您不能使用同一個鍵擁有多個條目。看起來你想創建一個'item'條目,每個條目都是數組的一個元素... – 2011-06-02 10:07:25

+0

請根據答案查看更新後的問題。 – oshirowanen 2011-06-02 10:33:11

回答

10

試試這個:

<?php 
$channel = array(
    'title' => 'title goes here', 
    'link' => 'link here', 
    'description' => 'description', 
    'items' => array() 
); 
while($row = mysql_fetch_array($results)) 
{ 
    extract($row); 
    $channel['items'][] = array(
     'title' => $title, 
     'link' => $link, 
     'guid' => $guid, 
     'pubDate' => $date, 
     'description' => $description 
    ); 
} 
$channels = array($channel); 
$rss = (object) array('rss'=> array('channels'=>$channels)); 
$json = json_encode($rss); 
echo $json; 

?> 
1

是的,它應該是相當簡單的,沿

$the_data['rss']['channels']['title'] = $title; 
$the_data['rss']['channels']['link'] = $link; 
$the_data['rss']['channels']['description'] = $desc; 

,然後你的while循環中,你可以有線條的東西,

$the_data['rss']['channels']['items'][] = $row; 

終於陣列編碼,

json_encode($the_data); 
+0

請根據答案查看更新後的問題。 – oshirowanen 2011-06-02 10:33:26

+0

@oshirowanen很明顯,你只會得到一個項目,因爲你每循環迭代覆蓋項目。爲什麼不使用我發佈的代碼的中間行? – Ben 2011-06-02 10:48:25