te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Passing PHP array into Javascript through JSON to update Google Chart - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Passing PHP array into Javascript through JSON to update Google Chart - Stack Overflow

programmeradmin3浏览0评论

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...

<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>

I would like to access these three arrays in Javascript to update my Google Chart dynamically.

<script type="text/javascript">

google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

var linevol = new Array;  // This would be the first array passed from PHP
var loanvol = new Array;  // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP

function drawChart() {
    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Cluster');
    data.addColumn('number', 'Loans');
    data.addColumn('number', 'Lines');

/* create for loops to add as many columns as necessary */

var len = jsonarray.length;

    data.addRows(len);

for(i=0; i<len; i++) {

data.setValue(i, 0, ' '+clusters[i]+'');     /* x-axis */
data.setValue(i, 1, linevol[i]);   /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]);   /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>

I have three PHP arrays that I've encoded with json... extra PHP code has been omitted because the arrays work properly.... Additionally, the HTML tags that call the google chart have been omitted for sake of brevity...

<?php
$encoded_line_volume = json_encode($LineVol) . "\n";
$encoded_loan_volume = json_encode($LoanVol) . "\n";
$encoded_cluster_name = json_encode($ClusterLine) . "\n";
?>

I would like to access these three arrays in Javascript to update my Google Chart dynamically.

<script type="text/javascript">

google.load("visualization", "1", {packages:["columnchart"]});
google.setOnLoadCallback(drawChart);

var linevol = new Array;  // This would be the first array passed from PHP
var loanvol = new Array;  // This would be the second array passed from PHP
var clusters = new Array; // This would be the third array passed from PHP

function drawChart() {
    var data = new google.visualization.DataTable();

    data.addColumn('string', 'Cluster');
    data.addColumn('number', 'Loans');
    data.addColumn('number', 'Lines');

/* create for loops to add as many columns as necessary */

var len = jsonarray.length;

    data.addRows(len);

for(i=0; i<len; i++) {

data.setValue(i, 0, ' '+clusters[i]+'');     /* x-axis */
data.setValue(i, 1, linevol[i]);   /* Y-axis category #1*/
data.setValue(i, 2, loanvol[i]);   /* Y-axis category #2*/
}
/*********************************end of loops***************************************/
  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 400, height: 240, is3D: true, title: 'Prospect Population', legend: 'right'});
}
</script>
Share Improve this question edited Nov 9, 2009 at 2:31 brussels0828 asked Nov 9, 2009 at 2:25 brussels0828brussels0828 3442 gold badges5 silver badges13 bronze badges 2
  • I'd love to help out, but your code is inplete and lacks formatting ;) – Justin Johnson Commented Nov 9, 2009 at 2:31
  • Justin... just reformatted it... should be plete now... – brussels0828 Commented Nov 9, 2009 at 2:38
Add a ment  | 

3 Answers 3

Reset to default 9

You probably want them to bee Javascript variables. When your php executes, it creates code your web browser then interprets. So you want to define javascript strings using php. For example:

<script type="text/javascript">
    var encoded_line_volume = <?php echo json_encode($LineVol) ?>;
    var encoded_loan_volume = <?php echo json_encode($LoanVol) ?>;
    var encoded_cluster_name = <?php echo json_encode($ClusterLine) ?>;
</script>

Then those variables are accessible to subsequent javascript.

This is how can you generate data dynamically from PHP, generate a JSON formatted output properly and read it from JavaScript (JQuery required) and load it to Google Visulization (Charts) API.

PHP (Server) Side:

function returnData() {
    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("Apple", 5);
    $data [] = Array ("Banana", 3);

    header('content-type: application/json');
    echo json_encode($data);
 }

Javascript (Client) Side:

var jsonData = null;

var jsonDataResult = $.ajax({
    url: dataURL,
    dataType: "json",
    async: false,
    success: (
        function(data) {
            jsonData = data;
        })
});

var data = new google.visualization.arrayToDataTable(jsonData);

This is one of the best examples I did which can help you : its tested and working nicely : Create two pages one called index.php and another one called get_json.php : This is not exactly the codes you posted but exactly the same idea and it answers the quetion.

the codes for index.php 

    <html>
    <head>
        <title>King Musa Graph</title>
        <!-- Load jQuery -->
        <script language="javascript" type="text/javascript" 
            src="http://ajax.googleapis./ajax/libs/jquery/1.7.0/jquery.min.js">
        </script>
        <!-- Load Google JSAPI -->
        <script type="text/javascript" src="https://www.google./jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", { packages: ["corechart"] });
            google.setOnLoadCallback(drawChart);

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

                var obj = jQuery.parseJSON(jsonData);
                var data = google.visualization.arrayToDataTable(obj);

                var options = {
                    title: 'King Musa'
                };

                var chart = new google.visualization.LineChart(
                            document.getElementById('chart_div'));
                chart.draw(data, options);
            }

        </script>
    </head>
    <body>
        <div id="chart_div" style="width: 900px; height: 500px;">
        </div>
    </body>
    </html> 

codes for get_json.php
<?php

    $data = Array ();
    $data [] = Array ("Name", "Value");
    $data [] = Array ("PHP", 78);

    $data [] = Array ("JAVA", 1000);
  $data [] = Array ("HTML", 129);


    $table = json_encode($data);
   // header('content-type: application/json'); 

    echo $table ; // this line is important it should be not disabled 

?>
发布评论

评论列表(0)

  1. 暂无评论