在 PHP 中将其他数据附加到数组


Appending additional data to an array in PHP

我使用 PHP 从 MYSQL 数据库请求数据。我要求的数据是歌曲信息,例如"艺术家","标题"等...

我想将服务器的当前时间附加到结果中。这样做的原因是,我可以计算歌曲何时在客户端计算机上结束,而无需请求两个 PHP 脚本。

以下是用于 MYSQL 数据检索的 PHP 代码:

<?php
date_default_timezone_set('Europe/London');
header("Cache-Control: no-cache");
// open DB connection
require_once("DbConnect.php");
// fetch playlist
$result = $db->query(
    "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`, `picture` "
   ."FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ");
// put into array
while ($row=$result->fetch_object()) $list[] = $row;
// encode and send result
echo json_encode ($list);
?>

当前请求输出如下所示:

注意:这只是一列数据,您将看到我实际上请求"DESC LIMIT 5"

*[{"艺术家":"Brothers in Progress & Venditti Bros",

"title":"庄园真实项目(豪尔赫·武井混音)",

"标签":"丹策",

"专辑年":"2013",

"date_played":"2014-11-24 20:45:28",

"持续时间":"12215",

"picture":"az_B111860__Brothers in Progress & Venditti Bros.jpg"}]***

所以这里一切都很好,只是一个标准的数据请求。

我现在想做的是以某种方式将服务器的时间(以毫秒为单位)添加到数组中。

是否可以以某种方式将以下代码的输出(以毫秒为单位的服务器时间)添加到数组中的第一个结果中。

<?php
date_default_timezone_set('Europe/London');
$serverTime = round(microtime(true) * 1000);
echo json_encode($serverTime);
?>  

非常感谢您抽出宝贵时间浏览我的问题,希望您能帮助我获得我正在寻找的结果......!

你的问题的简单答案是,你可以修改你的循环。见下文。但正确答案是马克·

// put into array
while ($row=$result->fetch_object()) {
    // If this is the first row of the result...
    if (empty($list)) {
        $row['ServerTime'] = round(microtime(true) * 1000);
    }
    $list[] = $row;
}

它将最终出现在 JSON 的第一个元素中。或者你可以显式地这样做(并假设至少有一个结果......

$list[0]['ServerTime'] = round(microtime(true) * 1000);

请注意,客户端/服务器同步不是那么简单。由于多种原因(例如JSON传输时间),会出现轻微错误。

Marc B 答案的粗暴实现是在输出之前立即添加数据

// And one thing I forgot - always best to specify type, and charset.
// Some JS libraries may balk at the output otherwise.
Header('Content-Type: application/json;charset=utf8');
json_encode(array(
    'ServerTime' => round(microtime(true)*1000),
    'list' => $list
));

不要在 json 结果中嵌入时间。这是混合不同的数据。它是json,只需围绕它构建一个结构:

$data = array();
$data['dbdata'] = $list;
$data['servertime'] = microtime(true);
echo json_ecode($data);

然后在您的客户端中,您的所有数据库结果都在 data.dbdata 中,data.servertime是您的时间戳。