如何在php

时间:2016-03-16 04:28:50

标签: 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"},{"ismy":"0"},{"time":"close"},{"img":"1.JPG"}]}

期望的结果是:

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

这有什么不对吗?请帮帮我。

2 个答案:

答案 0 :(得分:1)

使用此代码: -

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

答案 1 :(得分:0)

问题是您使用array_push功能的缩短版本四次。你真正想要做的是在结果数组中添加一个元素,尝试使用:

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