簡體   English   中英

嘗試使用php中的json_encode()以json格式輸出

[英]Trying to get output in the json format using json_encode() in php

我正在嘗試輸出為:

{
   "1":{
      "word":"Apple",
      "definition":"This is a Fruit"
   },
   "2":{
      "word":"Grapes",
      "definition":"This is a Fruit too"
   },
   .
   . //so on
   .

}

我的php7源代碼( main.php )是:

<?php
require 'configure.php';

$query = "SELECT * from entries where word LIKE 'Z%'";
$result = $conn->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);

$marks = array();

while ($row = $result->fetch_array()) {
    $marks[] =  array($row['sN'] => array(
        "word" => $row['word'],
        "definition" => $row['definition']
    ));     
}

var_dump(json_encode($marks));//(json_encode($marks));

/* free result set */
$result->free();

mysqli_close($conn);
?>

下面給出的代碼生成我想要的輸出:

$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
echo json_encode($marks);

我正在嘗試在我的main.php中應用關聯數組的概念如何通過在上面的main.php中使用LOOP來獲得所需的json輸出?

嘗試使用JSON_FORCE_OBJECT作為json_encode()函數的參數。 像這樣..

echo json_encode($marks,JSON_FORCE_OBJECT);

JSON_FORCE_OBJECT :使用非關聯數組時輸出對象而不是數組。 當輸出的接收者期望一個對象並且該數組為空時特別有用。

我認為問題在於如何分配$marks數組

while ($row = $result->fetch_array()) {
    $marks[$row['sN']] = array(
        "word" => $row['word'],
        "definition" => $row['definition']
    );     
}

並獲得0索引數組

$index = 0;
while ($row = $result->fetch_array()) {
    $marks[$index] = array(
        "word" => $row['word'],
        "definition" => $row['definition']
    );
    $index++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM