JSON数据数组查询

时间:2013-11-29 23:45:46

标签: mysql sql json

我正在使用jsonTable将数据解析到Google表格中,并且工作正常。现在我有一个问题是同时添加多个查询并仅在已定义的两列数组中显示数据。这是我的代码:

$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error()); 

$table = array();
$table['cols'] = array(
 array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')

);
$rows = array();
while ($nt = mysql_fetch_array($data))

{

$temp = array();

$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);

// insert the temp array into $rows
$rows[]['c'] = $temp;

}
$table['rows'] = $rows;
$jsonTable = json_encode($table); 

我的第一个问题是我想在$ data中添加多个查询,每个查询都会给出一个结果。我的下一个问题是我想在上面的列中显示多个查询的数据,定义为距离左。在车辆列中,我想在$ temp(第1行)中添加如上所示的静态数据。我搜索了很多,我很困惑如何做到这一点。请帮我,我想显示这样的表:

Vehicle            Distance Left

nextoilchange      500
nextfilter         300
nextcheckup        400

1 个答案:

答案 0 :(得分:0)

我没有测试过这个。如果不是不工作尝试这样的事情。

<?php 

$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());

$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] =  array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));

foreach($table as $key=>$eachtable)
{
    $cols = $eachtable['cols'];

    while ($nt = mysql_fetch_array($newdata))
    {

        foreach($cols as  $key1=>$each_col)
        {
            if($each_col['label'] == $nt)  //you have match the conditions
            {
                $row[$key1] = $nt['yourvalue'];
            }
            else
            {
                $row[$key1] = $nt['yourvalue1'];
            }
            $rows[] = $row;
        }
    }
    $table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);