将php数组转换为单个JSON对象

时间:2014-01-09 19:42:30

标签: php json

我遇到的问题是如何将我的php数组转换为JSON对象。无论我尝试什么,我都可以将所有内容打印为多个对象,或者将其显示为null。将其包装在pre tags中,这是我得到的最接近的内容:

我的代码:

$content = mysqli_query($dbcon, 
  "SELECT title, last_name AS lastname
   FROM revision, field_last_name
   WHERE vid = entity_id;"
);

echo "<pre>";
while($row = mysqli_fetch_array($content))
{
  print json_encode($row);
  print '<br/>';
}
echo "</pre>";

我的输出:

{"0":"John Apple","title":"John Apple","1":"Apple","lastname":"Apple"}
{"0":"Kumar Patel","title":"Kumar Patel","1":"Patel","lastname":"Patel"}
{"0":"Michaela Quinn","title":"Michaela Quinn","1":"Quinn","lastname":"Quinn"}
{"0":"Peyton Manning","title":"Peyton Manning, MD","1":"Manning","lastname":"Manning"}
{"0":"John Doe","title":"John Doe","1":"Doe","lastname":"Doe"}
{"0":"Jane Lee","title":"Jane Lee","1":"Lee","lastname":"Lee"}
{"0":"Dan McMan","title":"Dan McMan","1":"McMan","lastname":"McMan"}
{"0":"Yu Win","title":"Yu Win","1":"Win","lastname":"Win"}

我的两个问题是:

1)当我想要的只是"0":"John Apple""1":"Apple"时,为什么会有"title":"John Apple""lastname":"Apple"

2)为什么一切都显示为多个对象?

谢谢!

--- --- EDIT

$ arr = array()

echo "<pre>";   

while($row = mysqli_fetch_assoc($content))
{     
  $arr[] = $row;
}

print $arr;
echo "</pre>";

3 个答案:

答案 0 :(得分:1)

改变这个:

while($row = mysqli_fetch_array($content))
{
  print json_encode($row);
  print '<br/>';
}

对此:

$row = mysqli_fetch_assoc($content);
json_encode($row);

答案 1 :(得分:1)

field_last_name是你的表名吗?你可以在查询中通过表名如revision.title来区分每个列名前缀,并获取单个数组中的所有数据然后json_encode吗?

   $content = mysqli_query($dbcon, 
      "SELECT title, last_name AS lastname
       FROM revision, field_last_name
       WHERE vid = entity_id;"
    );
    $arr = array();

    echo "<pre>";
    while($row = mysqli_fetch_assoc($content))
    {
      $arr[] = $row;
    }
      print_r(json_encode($arr));


    echo "</pre>";

答案 2 :(得分:0)

...因为你要打印出多个对象。如果您想要一个数组的单个对象,则需要将mysql_fetch_assoc的结果(请参阅覆盖字段名称与位置的其他答案)附加到数组中,然后一次性json_encode数组。例如:

$myarray = array();
while($row = mysqli_fetch_assoc($content))
{
  $myarray[] = $row;
  print '<br/>';
}
print json_encode($myarray);