簡體   English   中英

PHP JSON到Google Chart API

[英]PHP json to google chart api

我在將php生成的json數組解析為Google圖表時遇到問題。 我已經包括了Jquery,但是有些我不知道如何解析我的json數據。 我運行一個MySQL查詢以從數據庫中檢索數據。 然后,我用php json_encode對查詢結果進行編碼。

我使用ajax從我的php文件中獲取json數據。

getData.php:

<?php
function get_meta_values( $key, $type = 'workout', $status = 'publish' ) {
  global $wpdb;
  $user_ID = get_current_user_id();

  if ( empty( $key ) )
    return;

  $r = $wpdb->get_results(
    $wpdb->prepare( "
      SELECT pm.meta_value, p.post_date FROM {$wpdb->postmeta} pm
      LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
      INNER JOIN $wpdb->term_relationships
      ON (p.ID = $wpdb->term_relationships.object_id)
      INNER JOIN $wpdb->term_taxonomy
      ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
      WHERE pm.meta_key = '%s' 
      AND $wpdb->term_taxonomy.taxonomy = 'category'
      AND $wpdb->term_taxonomy.term_id IN (4)
      AND p.post_status = '%s' 
      AND p.post_type = '%s'
      AND p.post_author = $user_ID
      ORDER BY pm.meta_value DESC ",
    $key,
    $status,
    $type));

    if ( $r ) {
      $user_ids = wp_list_pluck( $r, 'post_date' );
      cache_users( $user_ids );
    }

    return $r;
}
$workout_history = get_meta_values( '1_rep', 'workout' );
echo json_encode($workout_history);

?>

包含圖表的頁面:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", { packages: ["corechart"] });
  google.setOnLoadCallback(drawChart);

  function drawChart() {
    var jsonData = $.ajax({
      url: "http://localhost:41175/wp-content/themes/wordpress-bootstrap-master/getData.php",
      dataType: "json",
      async: false
    }).responseText;

  var obj = window.JSON.stringify(jsonData);
  var data = google.visualization.arrayToDataTable(obj);

  var options = {
    title: 'Test'
  };

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

當我嘗試回顯我的json文件時,它看起來像這樣:

[
  {
    "meta_value":"999",
    "post_date":"2014-04-12 18:21:51"
  },
  {
    "meta_value":"1",
    "post_date":"2014-04-12 18:58:20"
  }
] 

對我做錯了什么建議嗎?

https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable

似乎您的JSON數據集不適用於該方法。 它應該是(在javascript中):

var data = [
    ['metavalue', 'post_date'],
    ['999', '2014-04-12 18:21:51'],
    ['1', '2014-04-12 18:58:20']
]

在JSON中等於:

[["metavalue","post_date"],["999","2014-04-12 18:21:51"],["1","2014-04-12 18:58:20"]]

因為我不知道$workout_history的來源,所以我無法幫助您解決該問題。

return $r之前,對象圖不正確,請執行以下操作:

$results = array();
$result[] = array_values($r);
return $result;

或者,您可以像這樣構建一個數組數組:

$results = array();
$result[] = array($r['message_type'], $r['post_date']);
return $result;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM