如何在php中现有json对象中添加动态键值对

如何在php中现有json对象中添加动态键值对,php,mysql,json,Php,Mysql,Json,我想知道如何在执行期间在Json对象数组中添加动态键/值对 $result2来自数据库查询结果 while( $row = mysql_fetch_assoc($result2) ) { $result_show[]=$row; $result_show[]['ismy']='1'; $result_show[]['time']='close'; $result_show[]['img'] = $path; } 我的结果是: {"results":[{"id":"412"},{"is

我想知道如何在执行期间在Json对象数组中添加动态键/值对

$result2
来自数据库查询结果

while( $row = mysql_fetch_assoc($result2) )
{
 $result_show[]=$row;
 $result_show[]['ismy']='1';
 $result_show[]['time']='close';
 $result_show[]['img']  = $path;
}
我的结果是:

{"results":[{"id":"412"},{"ismy":"0"},{"time":"close"},{"img":"1.JPG"}]}
{"results":[{"id":"412","ismy":"0","time":"close","img":"1.JPG"}]}
预期结果是:

{"results":[{"id":"412"},{"ismy":"0"},{"time":"close"},{"img":"1.JPG"}]}
{"results":[{"id":"412","ismy":"0","time":"close","img":"1.JPG"}]}

这有什么问题?请帮帮我。

问题是您正在使用该函数的缩短版本四次。您真正想做的是向结果数组中添加一个元素,请尝试以下操作:

while( $row = mysql_fetch_assoc($result2) ) {
  $row['ismy']   = '1';
  $row['time']   = 'close';
  $row['img']    = $path;
  $result_show[] = $row;
}

问题是您四次使用该函数的缩短版本。您真正想做的是向结果数组中添加一个元素,请尝试以下操作:

while( $row = mysql_fetch_assoc($result2) ) {
  $row['ismy']   = '1';
  $row['time']   = 'close';
  $row['img']    = $path;
  $result_show[] = $row;
}
使用此代码:-

<?php
$i = 0;
while( $row = mysql_fetch_assoc($result2) ) {
{
    $result_show[$i]=$row;
    $result_show[$i]['ismy']='1';
    $result_show[$i]['time']='close';
    $result_show[$i]['img']  = $path;
     $i++;
}
?>

使用以下代码:-

<?php
$i = 0;
while( $row = mysql_fetch_assoc($result2) ) {
{
    $result_show[$i]=$row;
    $result_show[$i]['ismy']='1';
    $result_show[$i]['time']='close';
    $result_show[$i]['img']  = $path;
     $i++;
}
?>


yes获得答案和所需输出。yes获得答案和所需输出。