繁体   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