2013-07-09 92 views
0

如何將數組追加到多維數組?當它通過循環時,它需要將數據添加爲數組以創建多個數組。它編碼爲json併發送到Android手機。如何將數組添加到多維數組?

相關代碼:

$data = array(
    "articles" => array(
     array(
      'id'=> "4335", 
      'cat'=> "Lifestyle", 
      'title'=> "Welcome to field and rural life", 
      'url'=> "http://www.fieldandrurallife.com" 

     ), 
     array(
      'id'=> "4336", 
      'cat'=> "Lifestyle", 
      'title'=> "Thank You", 
      'url'=> "www.thankyou.com" 

     ) 
    ) 
); 

while($row = mysql_fetch_array($sql)) 
{ 
    $id = $row["id"]; 
    $cat = $row["category"]; 
    $title = $row["title"]; 
    $url = $row["url"]; 

    // HOW DO I ADD THIS INTO THE ARTICLES ARRAY?? 
// array(
//  'id'=> $id, 
//  'cat'=> $cat, 
//  'title'=> $title, 
//  'url'=> $url 
//  ) 

} 
+4

$數據[ '物品'] [] =陣列( 'ID'=> $ ID, '貓'=> $貓, '標題'=> $標題, 'URL'=> $網址); – user20232359723568423357842364

回答

2

簡單:

while($row = mysql_fetch_array($sql)){ 
    $id = $row["id"]; 
    $cat = $row["category"]; 
    $title = $row["title"]; 
    $url = $row["url"]; 

    $data['articles'][] = array(
          'id'=> $id, 
          'cat'=> $cat, 
          'title'=> $title, 
          'url'=> $url 
    ) 

} 
+0

This Works,Thank You! :) –

0

使用PHP的方法:

array_push($data["article"], $row); 
1

嘗試當您從數據庫提取使用array_push與json_encode

,如果你只有p你需要的列,然後直接將行推到數組上,因爲它已經是一個數組了。

while($row = mysql_fetch_array($sql)) 
{ 
    // Add your new array to the array 
    array_push($data['articles'], $row); 
} 

// Then you can encode your array to JSON like so. 
$json_version = json_encode($data);