1

I'm trying to make a pie chart to display data of operating systems, and am counting the operating system of each individual client with the following SQL query

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

I then put them inside an array with the following PHP

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

This outputs the following when json_encode'd:

{"AAA":"1","Windows 7 x86":"12"}

However, the pie chart javascript plugin requires the following markup

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

What would be the correct PHP syntax for me to use?

3
  • Note: AAA is just a random os name Commented Jan 6, 2014 at 10:55
  • show the code for piechart too or check the pie chart api Commented Jan 6, 2014 at 10:56
  • Then you building it wrongly, you should be building an array of dictionaries that will have label and data as key and add values against it. Commented Jan 6, 2014 at 10:58

3 Answers 3

1

Use label & data as association

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

and then use mysql_fetch_assoc

$data=array();
while($row=$query->fetch_assoc()){
 $data[]=$row;
}
return json_encode($data);
Sign up to request clarification or add additional context in comments.

Comments

1

Can you try this,

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

2 Comments

This returns {"label":"Windows 7 x86","data":"12"}. The AAA os seems to have disappeared.
I think you meant $count[]['label] instead of $count['label'][].
0
$outputData = array();

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

return json_encode($outputData);

2 Comments

I'm new here, so I'm figure out how to give good answers, but you mean explaining what exacly there is wrong, and how to adjust the code to get that what the question owner wants?
No Nothing wrong in your answer.e.g. As you created outputData array and assign value into it. So this is the difference or correction from OP code. So if you explain these thing it will more better to understand to others as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.