从mysql数据库创建json对象

时间:2013-10-23 18:03:02

标签: php mysql json

您好我想弄清楚如何使用php和mysql创建一个非常特定格式的json对象:

我的mysql表看起来像这样(不是最漂亮的,我知道):

CREATE TABLE IF NOT EXISTS `room120` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timestamp_start` datetime NOT NULL,
  `timestamp_end` datetime NOT NULL,
  `month` int(2) NOT NULL,
  `day` int(2) NOT NULL,
  `year` int(4) NOT NULL,
  `name` text NOT NULL,
  `email` text NOT NULL,
  `phone` text NOT NULL,
  `title` text NOT NULL,
  `start` varchar(5) NOT NULL,
  `end` varchar(5) NOT NULL,
  `approved` enum('true','false','new') NOT NULL DEFAULT 'new',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

我如何看待我的JSON对象:

[
    "10-23-2013": {
        0: {
            id : 1,
            title : "Hello World",
            time : "8:00 am - 10:00 am"
        },
        1: {
            id : 2,
            title : "Hello Universe",
            time : "1:00 pm - 3:00 pm"
        }
    }
]

我有我的cuurent php循环,它构建了id和title部分,但是我在构建具有日期的部分时遇到了问题。

这是我的php循环(是的,我知道没有用于构建日期部分的代码,我正在试图解决它。):

$return_arr = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
    $date = str_pad($row[month], 2, "0", STR_PAD_LEFT).'-'.str_pad($row[day], 2, "0", STR_PAD_LEFT).'-'.$row[year];
    $start_time = DATE("g:i a", STRTOTIME($row[start]));
    $end_time = DATE("g:i a", STRTOTIME($row[end]));

    $row_array[id] = $row[id];
    $row_array[title] = $row[title];

    array_push($return_arr, $row_array);
}
echo json_encode(array("event" => $return_arr));

目前返回的内容如下:

Object {event: Array[15]}
  event: Array[15]
    0: Object
      id: "1"
      title: "Hello World"

1 个答案:

答案 0 :(得分:3)

您需要在$return_arr另一个子阵列行中存储。看这里:

$return_arr = array();
while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {

    $date = str_pad($row[month], 2, "0", STR_PAD_LEFT).'-'.str_pad($row[day], 2, "0", STR_PAD_LEFT).'-'.$row[year];
    $start_time = DATE("g:i a", STRTOTIME($row[start]));
    $end_time = DATE("g:i a", STRTOTIME($row[end]));

   // create rowArr
    $rowArr = array(
        'id' => $row['id'],
        'title' => $row['title'],
        'time' => $startTime . ' - ' . $endTime
    );

    // store rowArr in $return_arr
    $return_arr[$date][] = $rowArr;

}

// display json encode

echo json_encode(array("event" => $return_arr));

现在你的$return_arr是一个多维数组,应该很好地回应。