将MySQL数组转换为json数组

时间:2014-01-06 10:55:35

标签: javascript php mysql arrays json

我正在尝试制作饼图以显示操作系统的数据,并使用以下SQL查询计算每个客户端的操作系统

SELECT os, COUNT( * ) AS count FROM clients GROUP BY os

然后我将它们放在一个包含以下PHP

的数组中
$query->execute();
$count = array();
while($row = $query->fetch()){
 $currOS = $row['os'];
 $count[$currOS] = $row['count'];
}
return json_encode($count);

当json_encode'd:

时输出以下内容
{"AAA":"1","Windows 7 x86":"12"}

但是,饼图javascript插件需要以下标记

var data = [
 { label: "AAA", data: 50},
 { label: "Windews 7", data: 7},
 { label: "Windews XP", data: 8},
 { label: "Windows 8", data: 9}
]; 

我使用的正确PHP语法是什么?

3 个答案:

答案 0 :(得分:1)

你能试试吗,

    while($row = $query->fetch()){
        $currOS = $row['os'];
        $count[]['label'] = $currOS;
        $count[]['data'] = $row['count'];
    }

答案 1 :(得分:1)

使用标签& 数据关联

SELECT os AS label , COUNT( * ) AS data FROM clients GROUP BY os

然后使用mysql_fetch_assoc

$data=array();
while($row=$query->fetch_assoc()){
 $data[]=$row;
}
return json_encode($data);

答案 2 :(得分:0)

$outputData = array();

while($row = $query->fetch())
{
    $outputData[] = array(
        'label' => $row['os'],
        'data' => $row['count'],
    );
}

return json_encode($outputData);