如何从数据库动态创建json数组

时间:2016-03-21 18:34:54

标签: database

我有一个表,其中包含一些员工的名字和姓氏。现在我的问题是如何动态创建一个json数组,如:

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

1 个答案:

答案 0 :(得分: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;