以自定义格式编码php记录集

时间:2016-06-09 08:16:13

标签: php dreamweaver

我目前使用Dreamweaver创建了一个记录集,并以json格式对结果进行编码,效果很好。

记录

$maxRows_rs_feeds = 3;
$pageNum_rs_feeds = 0;
if (isset($_GET['pageNum_rs_feeds'])) {
  $pageNum_rs_feeds = $_GET['pageNum_rs_feeds'];
}
$startRow_rs_feeds = $pageNum_rs_feeds * $maxRows_rs_feeds;

mysql_select_db($database_vivalooks, $vivalooks);
$query_rs_feeds = "SELECT fname,lname FROM profile";
$query_limit_rs_feeds = sprintf("%s LIMIT %d, %d", $query_rs_feeds, $startRow_rs_feeds, $maxRows_rs_feeds);
$rs_feeds = mysql_query($query_limit_rs_feeds, $vivalooks) or die(mysql_error());
$row_rs_feeds= mysql_fetch_assoc($rs_feeds);

if (isset($_GET['totalRows_rs_feeds'])) {
  $totalRows_rs_feeds = $_GET['totalRows_rs_feeds'];
} else {
  $all_rs_feeds = mysql_query($query_rs_feeds);
  $totalRows_rs_feeds = mysql_num_rows($all_rs_feeds);

}
$totalPages_rs_feeds = ceil($totalRows_rs_feeds/$maxRows_rs_feeds)-1;

 do { 

 echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));

mysql_free_result($rs_feeds);

记录集结果

{"fname":"Benjamin","lname":"Blay"}{"fname":"Alfread","lname":"Mark"}{"fname":"yaa","lname":"tiwaa"}

但我希望结果像这样编码

[{"fname":"Benjamin","lname":"Blay"},{"fname":"Alfred","lname":"Mark"},{"fname":"yaa","lname":"tiwaa"}]

3 个答案:

答案 0 :(得分:0)

尝试:

do { 
     $rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));

echo json_encode($rows);

答案 1 :(得分:0)

尝试

do { 
    $json[]=json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "[".implode(", ", $json)."]";

OR

do { 
     $rows[] = $row_rs_feeds;
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));

echo json_encode($rows);

答案 2 :(得分:0)

您可以将循环更改为:

echo "[";
$count = 0;
do { 
    if($count !== 0) 
        echo ",";
    $count++;
    echo json_encode($row_rs_feeds);
} while ($row_rs_feeds = mysql_fetch_assoc($rs_feeds));
echo "]";

$ count只是跳过第一个“,”所以你没有得到[,{...},{...}]或者你可以把它像假/真......我只是可以'现在记住,如果你有10k步循环,那会更好......