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 我下载图形界面重启完就变成这样了,打字也打不了,动也动不了,该怎么解决(操作系统-centos)
  • ¥15 VBA中在窗体中遍历所有checkbox控件,提取出被选中的checkbox的caption值
  • ¥15 在Ubuntu上有什么命令,或者是系统文件能告诉我链接nvme ssd的pcie槽位是不是支持热插拔功能?
  • ¥15 ansys license许可证问题
  • ¥20 QQ号和密码都能正常登录微信 QQ号和密码登录微信显示密码错误
  • ¥15 qiankun主应用注册子应用提示跨域
  • ¥15 单片机RTOS Kernel与应用分离开发,Kernel如何调起应用?
  • ¥15 快手小店商家版APP怎么第三方APP跳转到指定用户聊天界面
  • ¥15 为什么AVL fire软件仿真时的步长改变了,仿真结果也会改变
  • ¥100 如何帮我写一个java小游戏