无法使用foreach为google chart json打印多维数组

时间:2017-01-23 17:56:05

标签: php arrays multidimensional-array google-visualization

我正在尝试使用json创建谷歌折线图。根据此页面Building array and formatting JSON for Google Charting API,行必须类似于

$array['rows'][] = array('c' => array( array('v'=>'20-01-13'), array('v'=>22)) );

用于json编码。 我目前的代码是

$connectDb=@dbconnect::getSettings();
$query=$connectDb->prepare("SELECT timestamp, tottrdqty FROM {$database} WHERE symbol IN(?,?) AND series=? AND timestamp BETWEEN ? AND ? ORDER BY timestamp AND symbol");
$query->bind_param('sssss',$code,$code2,$series,$firstDate,$lastDate);
$query->execute();
$result=$query->get_result();
$query->close();
$connectDb->close();

while ($row =mysqli_fetch_assoc($result)) {

    $array[$row['timestamp']][] = $row['tottrdqty'];

}

/*foreach ($array as $date => $records)
{ echo $date . '<br />';
        foreach ($records as $record)
                { echo $record . '<br />'; }

}*/

$json_array=[];
$json_array['cols'][] = array('type' => 'date');
$json_array['cols'][] = array('type' => 'number');
$json_array['cols'][] = array('type' => 'number');
foreach ($array as $date => $records)
{


    $json_array['rows'][] = array('c' => array( array('v'=>"$date"),
foreach ($records as $record){
array('v'=>"$record"),
}       
        ));
    }

print json_encode($json_array);`

如果我删除第二个foreach一切正常,我怎么没有得到数组中的数字。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

尝试保存行数组,然后再添加到'rows',例如

$json_array=[];
$json_array['cols'][] = array('type' => 'date');
$json_array['cols'][] = array('type' => 'number');
$json_array['cols'][] = array('type' => 'number');
$json_array['rows'] = array();
foreach ($array as $date => $records) {
  $row_array = array(array('v'=>"$date"));
  foreach ($records as $record) {
    $row_array[] = array('v'=>$record);
  }
  $json_array['rows'][] = array('c' => $row_array);
}

print json_encode($json_array);

另外,为了方便谷歌,建议不要将行值包装在引号中,例如:

array('v'=>$record)

VS。

array('v'=>"$record")