2016-03-21 90 views
-1

我有一個包含姓和名的一些employees.Now我的問題是如何動態創建一個JSON數組就像一個表:如何從數據庫中動態創建JSON數組

"employees":[ 
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter","lastName":"Jones"} 

]

+0

你在哪個語言工作? – techblu3

+0

客戶端的java腳本和服務器端的php – rahul

回答

0

僞碼

rows= query("select firstName,lastName from employees") 

array a=[] //initialize empty array 
for (index,row) in rows 
    set a[index]=array('firstname'=>row.firstname,'lastname'=>row.lastname) 
end for 
b= json_encode(a) 

PHP實現

//in php connect to database 
$result = mysql_query("select firstName,lastName from employees"); 
if (!$result) { 
    echo 'Could not run query: ' . mysql_error(); 
    exit; 
} 
$a=array(); 
while($row = mysql_fetch_row($result)){ 
    $a[]=$row; 
} 
$b=json_encode($a); 
echo $b; 
+0

@rahul這樣回答你的問題嗎? – techblu3

+0

現在,我如何訪問第二行到$ b? 我可以使用$ b [2] – rahul

+0

$ b是json編碼的「字符串」,但如果您想要訪問第二行,則可以執行$ a [2] – techblu3