mysql php数组为特定格式

时间:2016-02-18 22:17:11

标签: php mysql arrays json format

我有以下代码:

   <?php
//mysqli query here

$table = array();
$table['cols'] = array(

array('id' => '', 'label' => 'Date', 'type' => 'date'),
array('id' => '', 'label' => 'Amount ', 'type' => 'number'),
); 
$rows = array();
foreach($result as $row){
$temp = array();

$date1 = date_create_from_format('Y-m-d H:i:s', $row['Date']);
$date2 = date_format($date1, 'm-d-Y');

$temp[] = array('v' => (string)'new Date("'.$date2.'")');
$temp[] = array('v' => (float) $row['Amount']);
$rows[] = array('c' => $temp);
}

$result->free();
$table['rows'] = $rows;
$jsonTable = json_encode($table, true);
echo $jsonTable;
?>

这会将以下数据输出到Google折线图:

{"cols":[
{"label":"Reading Date","type":"date"},
{"label":"Reading ","type":"number"},
"rows":[
{"c":[{"v":"new Date(10\/04\/2015)"},{"v":0.4}]},
{"c":[{"v":"new Date(02\/18\/2016)"},{"v":0.6}]}]}

但是我需要它采用以下格式才能使图表正常工作:

{"cols":[
      {"label":"Reading Date","type":"date"},
      {"label":"Cl Reading(mg\/l) ","type":"number"}
    ],
    "rows":[
      {"c":[{"v":new Date("10/04/2015")},{"v":0.4}]},
      {"c":[{"v":new Date("02/18/2016")},{"v":0.6}]}
    ]} 

所以我真的只关注一条需要改变的行,但似乎无法将其转化为我需要的格式:

$temp[] = array('v' => (string)'new Date("'.$date2.'")');

任何人都可以帮我这个吗?我知道它可能很简单,但似乎无法得到它..

2 个答案:

答案 0 :(得分:2)

更具可读性的东西会有所帮助

<?php
//mysqli query here

$table = array(
    'cols' => array(
        array('id' => '', 'label' => 'Date', 'type' => 'date'),
        array('id' => '', 'label' => 'Amount ', 'type' => 'number'),
    ),
    'rows' => array(),
);
foreach($result as $row){
    $date1 = date_create_from_format('Y-m-d H:i:s', $row['Date']);
    $date2 = date_format($date1, 'Y, m, d');   // this
    $table['rows'][] = array(
        'c' => array(
            array('v' => '\'Date('.$date2.')\''),  // and this
            array('v' => (float) $row['Amount']),
        )
    );
}

$result->free();
$jsonTable = json_encode($table, true);
echo $jsonTable;
?>

现在,需要改变的是什么?

修改
好的,我现在看到了...你不想生成JSON,你认为你想要生成javascript ..不要......只是保持JSON ...
(见What is the difference between JSON and Object Literal Notation?

事后生成Date对象。你将拥有日期字符串..只需传递日期构造函数。

编辑2:
Google Documentation - Dates and Times Using the Date String Representation
你只需要用引号括起新的日期(...)(

编辑3: 我更新了我的代码块以反映这个谷歌文档

答案 1 :(得分:0)

感谢布拉德肯特指出我正确的方向:

<?php

//mysql query 


    $table = array(
    'cols' => array(
        array('id' => '', 'label' => 'Date', 'type' => 'date'),
        array('id' => '', 'label' => 'Amount ', 'type' => 'number'),

    ),
    'rows' => array(),
);
foreach($result as $row){
    $date1 = date_create_from_format('Y-m-d H:i:s', $row['Date']);
    $date2 = date_format($date1, 'Y, m, d'); 
    $table['rows'][] = array(
        'c' => array(
            array('v' => 'Date('.$date2.')'), 
            array('v' => (float) $row['Amount'])

        )
    );
}

$result->free();
$jsonTable = json_encode($table, true);
echo $jsonTable;

    ?>