簡體   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