[英]Trying to get output in the json format using json_encode() in php
I'm trying to get output as: 我正在尝试输出为:
{
"1":{
"word":"Apple",
"definition":"This is a Fruit"
},
"2":{
"word":"Grapes",
"definition":"This is a Fruit too"
},
.
. //so on
.
}
my php7 source code( main.php ) is : 我的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);
?>
the code given below generates my desired output: 下面给出的代码生成我想要的输出:
$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);
I'm trying to apply the concept of associative arrays in my main.php how can I get the desired json output by using LOOP in my above main.php ? 我正在尝试在我的main.php中应用关联数组的概念如何通过在上面的main.php中使用LOOP来获得所需的json输出?
Try once using JSON_FORCE_OBJECT
as parameter of json_encode()
function. 尝试使用JSON_FORCE_OBJECT
作为json_encode()
函数的参数。 like this.. 像这样..
echo json_encode($marks,JSON_FORCE_OBJECT);
JSON_FORCE_OBJECT :Outputs an object rather than an array when a non-associative array is used. JSON_FORCE_OBJECT :使用非关联数组时输出对象而不是数组。 Especially useful when the recipient of the output is expecting an object and the array is empty. 当输出的接收者期望一个对象并且该数组为空时特别有用。
I think that the problem is in how you are assign your $marks
array 我认为问题在于如何分配$marks
数组
while ($row = $result->fetch_array()) {
$marks[$row['sN']] = array(
"word" => $row['word'],
"definition" => $row['definition']
);
}
and to get 0 indexed array you may 并获得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.