【问题标题】:PHP, MYSQL combining arrays from mysqli_fetch_arrayPHP,MYSQL 组合来自 mysqli_fetch_array 的数组
【发布时间】:2016-07-10 01:29:25
【问题描述】:

此代码是向FullCalendar 提供事件的函数的一部分,并在this 基础上稍作修改。我的编码知识充其量是最少的,现在已经学习了几天了。

  • 我的 MYSQL 数据分为两部分
  • 单独的日期和时间
  • 当前函数只接受 DATETIME 或 TIMESTAMP 格式

解决方案:

  • 将数组中的 DATE 和 TIME 组合成 DATETIME

让我们假设 MYSQL 表:

CREATE TABLE `test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(11) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `sdate` date NOT NULL,
  `stime` varchar(5) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `edate` date NOT NULL,
  `etime` varchar(5) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

假设函数:

{
    $events = array();
    $query = mysqli_query($con, "SELECT * FROM test");
    while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
    {
    $e = array();
    $e['id'] = $fetch['id'];
    $e['title'] = $fetch['title'];
    $e['start'] = array_push($e,$fetch['sdate'],$fetch['stime']);
    $e['end'] = array_push($e,$fetch['edate'],$fetch['etime']);

    array_push($events, $e);
    }
    echo json_encode($events);
}

问题:

$e['start'] = array_push($e,$fetch['sdate'],$fetch['stime']);
$e['end'] = array_push($e,$fetch['edate'],$fetch['etime']);

无论输入什么数据,结果都是“4”。添加的数组越多,即使数据是字符串,$e 的值也只会增加 1。对我来说这是一个进步,因为我尝试过其他方法,如 $a + $b 或 array_combine,设置多个数组实例,如:

$e['start'] = $fetch['sdate'];
$e['start'] = $fetch['stime'];
$e['end'] = $fetch['edate'];
$e['end'] = $fetch['etime'];

而且没有一个有效。甚至可以组合数组以产生除其中包含的数组数量之外的其他内容吗?非常感谢大家的时间和阅读。

【问题讨论】:

  • 您可以将两者(日期和时间)连接起来,并使用PHP中的date()函数使其成为有效的日期格式:$e['start'] = date("Y-m-d H:i:s", strtotime($fetch['sdate'].' '.$fetch['stime']));
  • 您的解决方案完全正确!

标签: php jquery mysql arrays ajax


【解决方案1】:

事实:

$e['start'] = array_push($e,$fetch['sdate'],$fetch['stime']);
$e['end'] = array_push($e,$fetch['edate'],$fetch['etime']);

如果您考虑 array_push 声明它返回的定义,返回 4 是完全正常的,我引用:

数组中元素的新数量。

由于有问题的数组是e,我们知道已经存在索引为startend 的元素,并且您的array_push 包含另外两个元素,这导致4。

所以关于array_push 的重要一点是它不返回一个数组,而是修改作为参数给出的第一个数组。因此,要使您的示例正常工作,您只需执行以下操作:

array_push($e['start'], $fetch['sdate'], $fetch['stime']);
array_push($e['end'], $fetch['edate'], $fetch['etime']);

【讨论】:

  • 尝试事先声明变量。我认为在正常情况下会起作用,但由于它是通过编码运行的,所以它不起作用?
猜你喜欢
  • 1970-01-01
  • 2014-05-29
  • 2018-02-11
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
相关资源
最近更新 更多