我正在尝试输出:
{
"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输出?
答案 0 :(得分:0)
尝试使用JSON_FORCE_OBJECT
作为json_encode()
功能的参数。喜欢这个..
echo json_encode($marks,JSON_FORCE_OBJECT);
JSON_FORCE_OBJECT :使用非关联数组时输出对象而不是数组。当输出的接收者期望一个对象并且该数组为空时特别有用。
答案 1 :(得分:0)
我认为问题在于如何分配$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++;
}