2012-07-15 2 views
0

내 웹 사이트에 Google 원형 차트를 갖고 싶습니다. 원형 차트는 데이터베이스의 데이터로 채워집니다. https://developers.google.com/chart/interactive/docs/php_example에서 몇 가지 예를 들었지만 JSON 형식에 관해서는 분실했습니다. 여기 Google 원형 차트 및 PHP

은 몇 가지 예입니다 : 나는 데이터베이스가 아닌 JSON 형식으로 저장된 데이터를

<?php 

// This is just an example of reading server side data and sending it to the client. 
// It reads a json formatted text file and outputs it. 

$string = file_get_contents("sampleData.json"); 
echo $string; 

// Instead you can query your database and parse into JSON etc etc 

?> 

: 여기

<html> 
    <head> 
<!--Load the AJAX API--> 
<script type="text/javascript" src="https://www.google.com/jsapi"></script> 
<script type="text/javascript" src="jquery-1.6.2.min.js"></script> 
<script type="text/javascript"> 

// Load the Visualization API and the piechart package. 
google.load('visualization', '1', {'packages':['corechart']}); 

// Set a callback to run when the Google Visualization API is loaded. 
google.setOnLoadCallback(drawChart); 

function drawChart() { 
    var jsonData = $.ajax({ 
     url: "getData.php", 
     dataType:"json", 
     async: false 
     }).responseText; 

    // Create our data table out of JSON data loaded from server. 
    var data = new google.visualization.DataTable(jsonData); 

    // Instantiate and draw our chart, passing in some options. 
    var chart = new google.visualization.PieChart(document.getElementById('chart_div')); 
    chart.draw(data, {width: 400, height: 240}); 
} 

</script> 
</head> 

<body> 
    <!--Div that will hold the pie chart--> 
    <div id="chart_div"></div> 
</body> 
</html> 

내가 길을 잃지 스 니펫 (getData.php)입니다 . MySQL 데이터베이스 쿼리를 사용하여 JSON 형식으로 어떻게 작업합니까? 몇 가지 예나 데모가 있다면, 고맙겠습니다.

답변

0

가장 먼저 할 일은 json_encode() 메소드에 대한 PHP 매뉴얼을 보는 것입니다. PHP로 JSON을 생성하는 방법에 대한 예제를 제공합니다. 당신이 당신의 JSON 데이터가 DB에 사용되는 것보다 특성에 다른 이름을 얻을 수 있도록 데이터베이스 열 이름을 변경해야 할 경우

// Get your data from DB 
$sth = mysql_query("SELECT ..."); 
// Create an array 
$rows = array(); 
// Loop over the DB result and add it to your array 
while($r = mysql_fetch_assoc($sth)) { 
    $rows[] = $r; 
} 
// Use json_encode() to turn the array into JSON 
print json_encode($rows); 

것은, 당신이 사용할 수 있습니다 여기에

another similar SO question에서 짧은 예이다 AS을 SQL에 저장하십시오.

SELECT blog_title as title ... 
+0

도움 주셔서 감사합니다. json이나 api 옵션에서 레이블을 설정해야합니까? –

+0

@ extra90 JSON-data는 차트의 레이블로 사용됩니다 (해당되는 경우). –

+0

나는 Google 차트에 대한 문서를 찾고 있었고 json은 올바른 json 형식이어야합니다. json_encode로는 충분하지 않습니다. 어떤 경험이 있습니까? –

0

단지 에코 PHP 결과는 var data = new google.visualization.DataTable([<?php echo $result ;?>]);

에서 유 전에서 같은 논리를 사용 해요, 내가 그것을 유에게 유용하다고 생각 형식

   ['Task', 'Hours per Day'], 
         ['Work',  11], 
         ['Eat',  2], 
         ['Commute', 2], 
         ['Watch TV', 2], 
         ['Sleep', 7] 

아래 로 따라 데이터베이스에서 데이터를 얻을 것이다 heat map