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

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?