如何为现有的mysql结果数组添加额外的属性

时间:2016-09-15 07:24:40

标签: php mysql

我使用以下方法存储mysql选择结果

 $getposts="select PD.PostID,PD.UserID,SUBSTR(PD.PostDescription,1,50) PostDescription,PD.PostTitle,UD.UserName,UD.ImagePath,UD.UserName,UD.CreateDate,UD.TimeZone from postdetails PD
  join userdetails UD on UD.UserID=PD.UserID";

$result = mysqli_query($dbcon,$getposts);
$rows = array();

while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}

echo json_encode($rows);

从上面的结果我想添加一些额外的字段,如下面的

while($r = mysqli_fetch_assoc($result)) {

 $date = new DateTime($r[CreateDate]);
 $date->setTimezone(new DateTimeZone($r[TimeZone]));

 //eg: $date->setTimezone(new DateTimeZone('+04'));
 $date->format('Y-m-d H:i:s');

    $rows[] = $r;
    $row.FormattedCreatedDate=$date;
}
echo json_encode($rows);

2 个答案:

答案 0 :(得分:0)

好像你可以在这里使用array_merge。请尝试以下代码。

$getposts="select PD.PostID,PD.UserID,SUBSTR(PD.PostDescription,1,50) PostDescription,PD.PostTitle,UD.UserName,UD.ImagePath,UD.UserName,UD.CreateDate,UD.TimeZone from postdetails PD
join userdetails UD on UD.UserID=PD.UserID";

$result = mysqli_query($dbcon,$getposts);
$rows = array();

while($r = mysqli_fetch_assoc($result)) {
    $date = new DateTime($r[CreateDate]);
    $date->setTimezone(new DateTimeZone($r[TimeZone]));

    //eg: $date->setTimezone(new DateTimeZone('+04'));
    $date->format('Y-m-d H:i:s');

    $rows[] = array_merge($r, array("FormattedCreatedDate"=>$date));//modify this one
    //$row =$date;//remove this line
}

echo json_encode($rows);

使用array_merge,您可以组合MySQL结果和可以在数组中传递的额外字段。

答案 1 :(得分:0)

我会按键 - >重视它,要做到这一点,你需要通过自动增量变量来控制密钥创建。

$i = 0;
while($r = mysqli_fetch_assoc($result)) {

    $date = new DateTime($r[CreateDate]);
    $date->setTimezone(new DateTimeZone($r[TimeZone]));

    //eg: $date->setTimezone(new DateTimeZone('+04'));
    $date->format('Y-m-d H:i:s');

    $rows[$i] = $r;
    $rows[$i]['FormattedCreatedDate'] = $date;
    $i++;
}