我有一个使用php制作的API,从SQL中获取并将其转换为JSON,工作正常。我唯一的问题是,我无法操纵这个PHP来获取我想要的JSON。解决方案我认为只是在我的api.php的$ outp中的位置..我在SQL中使用id作为主要我可以用它作为索引来显示像我预期的JSON吗?
感谢你,任何努力都会得到奖励
这是输出JSON:
{
talents: [
{
id: "1",
tag: "001",
name: "Jasmina",
images: "assets/images/Jasmina3.jpg",
images02: "assets/images/Jasmina4.jpg",
images03: "assets/images/Jasmina7.jpg",
skills: "Usher",
skills02: "Modeling",
indexing: "usher"
},
{
id: "2",
tag: "002",
name: "Bruna",
images: "assets/images/BrunaD17.jpg",
images02: "assets/images/BrunaD18.jpg",
images03: "assets/images/BrunaD10.jpg",
skills: "Usher",
skills02: "Modeling",
indexing: "usher"
}
]
}
以下是我预期的结果:
{
talents: [
1: {
tag: "001",
name: "Jasmina",
images: "assets/images/Jasmina3.jpg",
images02: "assets/images/Jasmina4.jpg",
images03: "assets/images/Jasmina7.jpg",
skills: "Usher",
skills02: "Modeling",
indexing: "usher"
},
2:{
tag: "002",
name: "Bruna",
images: "assets/images/BrunaD17.jpg",
images02: "assets/images/BrunaD18.jpg",
images03: "assets/images/BrunaD10.jpg",
skills: "Usher",
skills02: "Modeling",
indexing: "usher"
}
]
}
看一看我的API,请帮我玩那个$ outp。得到它。
<?php
//header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "application");
$result = $conn->query("SELECT * FROM talents");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"id":"' . $rs["id"] . '",';
$outp .= '"tag":"' . $rs["tag"] . '",';
$outp .= '"name":"' . $rs["name"] . '",';
$outp .= '"images":"'. $rs["images"] . '",';
$outp .= '"images02":"'. $rs["images02"] . '",';
$outp .= '"images03":"'. $rs["images03"] . '",';
$outp .= '"skills":"'. $rs["skills"] . '",';
$outp .= '"skills02":"'. $rs["skills02"] . '",';
$outp .= '"indexing":"'. $rs["indexing"] . '"}';
}
$outp ='{"talents":['.$outp.']}';
$conn->close();
echo($outp);
?>
答案 0 :(得分:2)
不要试图自己构建json,而是使用native startActivityForResult()。它解决了JSON的所有边缘情况。
您需要准备的只是一个关联数组,您可以逐个字段指定(就像我在示例中所做的那样,建议使用这种方式,因为您指定要发送给用户的确切字段,它会阻止敏感数据公开)或只是$outp[$rs["id"]] = $rs;
<?php
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "application");
$result = $conn->query("SELECT * FROM talents");
$outp = array();
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[$rs["id"]] = array(
"tag" => $rs["tag"],
"name" => $rs["name"],
"images" => $rs["images"],
"images02" => $rs["images02"],
"images03" => $rs["images02"],
"skills" => $rs["skills"],
"skills02" => $rs["skills02"],
"indexing" => $rs["indexing"]
);
}
$outp["talents"] = array($outp);
$conn->close();
echo (json_encode($outp));
?>