繁体   English   中英

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

[英]converting php array into a single JSON object

我有一个问题,我如何将我的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)为什么一切都显示为多个对象?

谢谢!

- -编辑 - -

$ arr = array()

echo "<pre>";   

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

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

改变这个:

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

对此:

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

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>";

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM