从 mysql 数据库创建 json 对象


Create json object from mysql database

嗨,我正在尝试弄清楚如何使用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"
        }
    }
]

我有一个构建 id 和标题部分的 cuurent php 循环,但我在构建具有日期的部分时遇到问题。

这是我的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"

您需要存储在另一个子数组行$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是一个多维数组,应该得到很好的回声。