动态地从php构建符合谷歌图表的json

时间:2016-01-24 05:33:19

标签: php mysql json

我想在这里实现一些目标,即从PHP构建符合谷歌图表的JSON对象。到目前为止,我已经在这里的一些用户的帮助下管理(谢谢你们)动态构建列,如下面的php脚本所示。

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Check if query GET parameters are defined

if (isset($_GET['date'])) {
    $parm = $_GET['date'];
    $sql = "SELECT
        DomesticInternational as 'DomesticInternational',  
        SUM(CASE WHEN (SalesYear='$parm') THEN 1 ELSE 0 END) AS 'Value'                   
        FROM 
        (   SELECT DomesticInternational,SalesYear
            FROM couponsummary 
            WHERE SalesYear='$parm'        
        )as Data 
        GROUP BY DomesticInternational";
}

// Run query, store in associative array

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $i = 0;
    foreach($row as $name => $val) {

        // We retrieve the mysqli field type, switch on them, and assign them to $type

        $finfo = mysqli_fetch_field_direct($result, $i);
        switch ($finfo->type) {
        case 253:
            $type = 'string';
            break;

        case 246:
            $type = 'number';
            break;

        default:
            $type = 'string';
        }

        // Constructs the column array

        $array['data']['cols'][] = array(
            'label' => $name,
            'type' => $type
        );

        // Constructs the cells array

        $c[] = array(
            "v" => $val
        );

        // echo $row[(string)$name];

        $i++;

    }

    // Constructs the rows array

    $array['data']['rows'] = array(
        array(
            'c' => $c
        )
    );
}
else {
    echo "0 results";
};

// We echo the json and enforce a numeric check on the values

echo $_GET['callback'] . '(' . json_encode($array, JSON_NUMERIC_CHECK) . ')';
$conn->close(); //We close the database connection here

JSON输出如下:

{
   "data": {
      "cols": [
         {
            "label": "DomesticInternational",
            "type": "string"
         },
         {
            "label": "Value",
            "type": "number"
         }
      ],
      "rows": [
         {
            "c": [
               {
                  "v": "D"
               },
               {
                  "v": 57499
               }
            ]
         }
      ]
   }
}

但是,查询实际上会返回:

+-----------------------+-------+
| DomesticInternational | Value |
+-----------------------+-------+
| D                     | 57499 |
| I                     | 24840 |
+-----------------------+-------+

因此在JSON中,而不是1 c [array],应该有两个,其中嵌套了2个v {object},但基本上跳过了查询返回的第二行:/。我真的不知道该怎么做,我很确定我不理解编程的基本原则,但请耐心等待,我刚开始学习:)请帮助大家。谢谢:)

0 个答案:

没有答案