将附加数据附加到PHP中的数组中

问题描述:

我使用PHP从MYSQL数据库请求数据。我要求的数据是歌曲信息,如“艺术家”,“标题”等...将附加数据附加到PHP中的数组中

我想追加到服务器的当前时间的结果。这样做的原因是,我可以计算歌曲在客户端计算机上何时结束,而无需请求两个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'

* [{ “艺术家 ”:“ 正在进行& Venditti兄弟兄弟”,

标题 ”:“ 庄园房地产项目(豪尔赫TakeiRemix)”,

标签 ”:“ Dantze”,

albumyear ”:“ 2013”​​,

date_played ”:“ 情节中字20时45分28秒”,

时间 ”:“ 12215”,

图片 ”:“ 进展& Venditti Bros.jpg az_B111860__Brothers”}] ***

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

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

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

<?php 
date_default_timezone_set('Europe/London'); 

$serverTime = round(microtime(true) * 1000); 

echo json_encode($serverTime); 
?> 

非常感谢您花时间浏览我的问题,希望您能帮助我获得我期待的结果......!

+0

你只希望它在数组中的第一个结果? – JRL 2014-11-24 21:11:31

+1

您可能想查看媒体活动。其中一人可能会为你工作:http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#mediaevents – 2014-11-24 21:20:24

之前添加的数据不嵌入在JSON结果的时间。这是混合不同的数据。这是JSON,只是建立一个围绕它来构建:

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

echo json_ecode($data); 

然后inyour客户端,你的所有DB结果是data.dbdata,并data.servertime是您的时间戳。

+0

非常感谢。这是相当优雅的。 – Justin 2014-11-24 22:49:42

明确回答你的问题是,你可以修改你的循环。见下文。但正确答案是B.马克

// 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传输时间,一次)。

蛮力实现马克·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 
));