doucheng7534 2014-01-09 19:42
浏览 41
已采纳

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

I am having an issue with how I am converting my php array into a JSON object. No matter what I try, I either print everything out as multiple objects or it comes out as null.Wrapping it in pre tags, here is the closest that I got it:

My code:

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

My output:

{"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"}

My two questions are:

1) Why is there a "0":"John Apple" and a "1":"Apple" when all I want is "title":"John Apple" and "lastname":"Apple" in my object?

2) Why is everything displaying as multiple objects?

Thanks!

---EDIT---

$arr = array()

echo "<pre>";   

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

print $arr;
echo "</pre>";
  • 写回答

3条回答 默认 最新

  • dqzve68846 2014-01-09 19:47
    关注

    field_last_name is your table name? can you distinguish each column name prefix by table name like revision.title in your query and get all data in a single array and then json_encode it?

       $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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?