php - 从 mysql 数据库创建 json 对象

标签 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"
        }
    }
]

我有构建 id 和标题部分的当前 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 是一个多维数组,应该很好地回显。

关于php - 从 mysql 数据库创建 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19549094/

相关文章:

php - 从phpmyadmin导入sql数据库时出错

php - SQL错误: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

php - 锁定MySQL中的最大值

jQuery 如何从 html 响应中获取正文内容

json - 在 Haskell 中将 JSON 字符串解析为记录

php - 为什么在匿名函数上使用 `eval` 时,使用 `unset` 之后不会释放内存?

mysql - 带有聚合函数的 SELECT CASE

mysql - only_full_group_by 不让我按我的意愿显示表格

mysql - 在 WHERE block 中使用条件在表中添加列

json - 如何正确地将非字符串值添加到 TJSONObject?