【发布时间】:2016-08-09 06:54:49
【问题描述】:
我的标题令人困惑..对此感到抱歉..无论如何..请查看我的代码:
<?php
include('../connectDB.php'); //connect to db
echo '{ ';
echo '"success": 1, ';
echo '"result": [ ';
$result = mysql_query("SELECT * FROM roominventory");
while($row = mysql_fetch_array($result)) { //start while
$getId = $row['id']; //get value
$getRoomId = $row['room'];
echo '{ ';
$ar = $row['arrival']; //assign value to variable
$dep = $row['departure'];
$date = str_replace('-', '/', $ar); //format the date
$formatArr = date('m/d/Y', strtotime($date));
$date2 = str_replace('-', '/', $dep); //format the date
$formatDep = date('m/d/Y', strtotime($date2));
$mSt = strtotime($formatArr) * 1000; //convert to milliseconds
$mEd = strtotime($formatDep) * 1000;
echo '"id": ' . '"' . $getId. '"' . ', ';
$resulta = mysql_query("SELECT * FROM rooms_amenities WHERE id='$getRoomId'");
while($rowa = mysql_fetch_array($resulta)) {
$getName = $rowa['name'];
}
echo '"title": ' . '"' . $getName . '"' . ', ';
echo '"url": ' . '"' . 'http://example.com' . '"' . ', ';
echo '"class": ' . '"' . 'event-warning' . '"' . ', ';
echo '"start": ' . '"' . $mSt . '"' . ', '; //echo the converted date
echo '"end": ' . '"' . $mEd . '" ';
echo '} ';
echo ', '; //comma (should only in between entries and not in the very end of the very last entry)
} //end while
echo '] ';
echo '}';
?>
现在这是文件的结果:
{ "success": 1, "result": [ { "id": "254", "title": "Standard Room 202", "url": "exampledotcom", "class": "event-warning ", "开始": "1470693600000", "结束": "1471384800000" } ] }
没问题。现在,问题是当我的数据库中的表中有超过 1 行时,结果会变成这样:
{ "success": 1, "result": [ { "id": "255", "title": "Standard Room 201", "url": "exampledotcom", "class": "event-warning ","开始":"1471903200000","结束":"1472076000000" },{"id":"256","title":"标准房间 202","url":"exampledotcom","class": “事件警告”,“开始”:“1471903200000”,“结束”:“1472076000000”},]}
注意最后一个条目“1472076000000”处的“逗号”},] }
我想要/预期的结果应该是这样的:
{ "success": 1, "result": [ { "id": "255", "title": "Standard Room 201", "url": "exampledotcom", "class": "event-warning ", "start": "1471903200000", "end": "1472076000000" }, { "id": "256", "title": "标准房 202", "url": " exampledotcom”,“class”:“事件警告”,“start”:“1471903200000”,“end”:“1472076000000”}]}
注意第一个条目之后和第二个条目之间的“逗号” { "id: "...}, { "id: "...} 并且最后一个条目之后没有逗号。
我试图在 while 循环的外部/结尾回显逗号。但结果,逗号只在最后一个条目,没有中间
如果到达最后一行,那么最后一个条目不应该有逗号。我不知道我怎样才能得到想要的结果。
还有其他方法/方法吗?喜欢使用数组/json_encode? ..但我不知道该怎么做
【问题讨论】:
-
json_encode() 是你的朋友,你永远不应该像这样构建 JSON 字符串
-
只需创建一个数组,然后对其进行编码,就更容易了。
-
要纠正你的代码,你应该把 echo ', ';在第一个“回声'{';”之前同时,在 if 语句中 if(isset($ar) { echo ', '; }
-
Stop stop stop using the deprecated MySQL libraries...
-
我还在学习使用 mysqli。对不起。我太原始了等我学会了再改。谢谢你的建议:)
标签: php mysql json while-loop encode