我需要JSON以下面的格式显示。对象是“用户”
{
"users": [{
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
}, {
"ver": "7.0",
"name": "Nougat",
"api": "API level 24"
}]
}
当我使用这个PHP时
<?php
$link = mysqli_connect("localhost", "***", "***", "***");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM users";
if ($result=mysqli_query($link, $query)) {
{
while($row =mysqli_fetch_assoc($result))
$emparray[] = $row;
echo json_encode($emparray);
}
} else {
echo "It failed";
}
?>
我回来了这个JSON
[{
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
}, {
"ver": "7.0",
"name": "Nougat",
"api": "API level 24"
}
}]
当我使用这个PHP时
<?php
$link = mysqli_connect("localhost", "***", "***", "***");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query = "SELECT * FROM users";
if ($result=mysqli_query($link, $query)) {
{
while($row =mysqli_fetch_assoc($result))
$emparray[] = $row;
echo json_encode(array('users' => $emparray),JSON_FORCE_OBJECT);
}
} else {
echo "It failed";
}
?>
我明白了
{
"users": {
"0": {
"ver": "1.5",
"name": "Cupcake",
"api": "API level 3"
},
"1": {
"ver": "7.0",
"name": "Nougat",
"api": "API level 24"
}
}
}
后者几乎是我需要的,但显示{“0”:而不是所需的[和]
任何人都可以帮忙纠正这个问题吗?
答案 0 :(得分:0)
尝试
if ($result = mysqli_query($link, $query))
{
while ($row = mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(array('users' => $emparray));
}
else
{
echo "It failed";
}
删除JSON_FORCE_OBJECT
常量。