我正在尝试将数据库值转换为json 在编码为json之前,我已经做了一些数组,但是返回的却不像我想要的那样, 有人请帮助我 我的代码是这样的
function createDataJson($ref){
$master_data = array();
// $data = array();
$sql = mysql_query("SELECT DISTINCT dataCode FROM tbl_master WHERE dataRefServices = '$ref'");
if(mysql_num_rows($sql)){
while($row = mysql_fetch_assoc($sql)){
$dataCode = $row['dataCode'];
$sql2 = mysql_query("SELECT DISTINCT asKey,asValue FROM tbl_master WHERE dataCode = '$dataCode' AND dataRefServices = '$ref'");
if(mysql_num_rows($sql2)){
while ($row2 = mysql_fetch_assoc($sql2)) {
$asKey = $row2['asKey'];
$asValue = $row2['asValue'];
$data->$asKey=$asValue;
}
$dat[] = $data;
}
$master_data = $dat;
}
}
return json_encode($master_data);
}
它返回这样,它只是复制最后一个数组
[
{
"code": "IT - 0004",
"main": "12",
"child": "14",
"name": "Laptop",
"brand": "Lenovo"
}, {
"code": "IT - 0004",
"main": "12",
"child": "14",
"name": "Laptop",
"brand": "Lenovo"
}
]
我正在寻找的格式如下:
[
{
"code": "IT - 0001",
"main": "12",
"child": "14",
"name": "Pavillion 15",
"brand": "Asus"
}, {
"code": "IT - 0002",
"main": "12",
"child": "14",
"name": "Envy 13",
"brand": "HP"
}
]
从此表:
请帮助我,真的在找它
有人可以帮我吗?我被困在这里。呵呵
答案 0 :(得分:0)
使用json_encode将数组转换为json。
echo json_encode($array_of_data_from_database);
这将发送JSON数据作为响应。