2013-02-25 53 views
0

所以這是我在PHP動態添加項目到數組PHP的中間

$data = array(
    "results" => array(
    "course" => "$cc", 
    "books" => array(
     "book" => 
     array( 
     //Place temp here; 
    ) 
    ) 
) 
); 

一部開拓創新的數組這是我有更多的數據在陣列中去,也可能是幾百個或者只是甚至一個

foreach ($my_array as $counter => $bc) { 
     $temp = array(
      "-id" => "$id[$counter]", 
      "-title" => "$title[$counter]", 
      "-isbn" => "$isbn[$counter]", 
      "-borrowedcount" => "$borrowedcount[$counter]" 
     ); 
    } 

因此它可以在一個有效的JSON的方式進行編碼,看起來像

{ 
"results": { 
    "course": "CC167", 
    "books": { 
    "book": [ 
    { 
     "-id": "585457", 
     "-title": "Beginning XNA 20 game programming : from novice to professional", 
     "-isbn": "1590599241", 
     "-borrowedcount": "16" 
    }, 
    { 
     "-id": "325421", 
     "-title": "Red Hat Linux 6", 
     "-isbn": "0201354373", 
     "-borrowedcount": "17" 
    }, 
    { 
     "-id": "424317", 
     "-title": "Beginner's guide to darkBASIC game programming", 
     "-isbn": "1592000096", 
     "-borrowedcount": "46" 
    }, 
    { 
     "-id": "437390", 
     "-title": "Objects first with Java : a practical introduction using BlueJ", 
     "-isbn": "0131249339", 
     "-borrowedcount": "89" 
    }, 
    { 
     "-id": "511094", 
     "-title": "Objects first with Java : a practical introduction using BlueJ", 
     "-isbn": "2006044765", 
     "-borrowedcount": "169" 
    } 
    ] 
    } 
} 
} 

謝謝您可以提供任何幫助

+0

array_splice()(http://www.php.net/manual/en /function.array-splice.php)是你正在尋找的功能 – 2013-02-25 12:03:31

+0

你遇到問題的具體部分是什麼? – PeeHaa 2013-02-25 12:03:35

+0

$ data ['results'] ['books'] + = array(// something) – sanj 2013-02-25 12:10:51

回答

3

一旦循環並添加了所有值,將book數組元素賦值爲$temp的值。

$data['results']['books'] = $temp; 

或者,循環第一,當您設置$data陣列,當你已經擁有的價值觀,你需要:

$data = array("results" => array("course" => "$cc", "books" => $temp));