【发布时间】:2017-07-16 02:46:18
【问题描述】:
我正在尝试将输出设为:
{
"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_encode($marks)的输出是什么?你期望得到什么? -
{"mohammad":{"physics":35,"maths":30,"chemistry":39},"qadir":{"physics":30,"maths":32, "化学":29},"zara":{"物理":31,"数学":22,"化学":39}}
-
我希望得到上面的输出..!
-
json_encode($marks)的输出是什么?你怎么能在你的数组中定义一些东西——单词和定义——并期望其他东西——物理、数学和化学——? -
@HassanAhmed,我粘贴了两个代码:一个是 main.PHP,我想在其中获取 JSON 格式的输出,另一个是我从教程中复制的代码(包括物理化学和数学) )。忘记价值观吧。我只是希望它们采用我在问题上方发布的格式。 LIKE { "1":{ "word":"Apple", "definition":"This is a Fruit" }, "2":{ "word":"Grapes", "definition":"This is a Fruit too " }, . . //很快 。 }
标签: php json associative-array php-7