Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何向mysql结果的现有数组添加额外属性_Php_Mysql - Fatal编程技术网

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

Php 如何向mysql结果的现有数组添加额外属性,php,mysql,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"

我正在使用下面的方法存储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);
看起来你可以在这里用。试试下面的代码

$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\u merge,您可以将MySQL结果和可以在数组中传递的额外字段组合起来。

我将对其进行键->赋值,要做到这一点,您需要通过一个autoincrement变量来控制键的创建

$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++;
}

我补充了一个答案。检查是否有帮助。