所以我有以下代码:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = [];
while ($r = mysqli_fetch_assoc($getUsers)) {
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}
print(json_encode($rows));
哪个输出:
[{"id":"1","name":"user1","skills":{"woodcutting":"6","mining":"10"}},{"id":"2","name":user2"}]
有两个问题:
skills
中获取所有数据除了id,或者至少在用json编码之前将其删除。我做错了什么?
答案 0 :(得分:0)
看起来你需要类似的东西:
while($r = mysqli_fetch_assoc($getSkills)) {
unset($r['id']);
$rows['skills'] = $r;
}
答案 1 :(得分:0)
id
unset($r['id'])
以从array() $r
中删除。在未设置id
之前,将id保留为变量,因为您将其用于下一个查询。 Point-2:可能skills
这些ID中没有数据存在。结果你没有得到skills
。建议您通过这些ID查询skills
表中是否存在任何数据。
while ($r = mysqli_fetch_assoc($getUsers)) {
$id = $r['id'];
unset($r['id']);
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '$id'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}
答案 2 :(得分:0)
要获取表id
中除skills
之外的所有列,您可以列出要选择的所有列,如下所示:
mysqli_query($db, "SELECT column1, column2, another_column FROM `skills` WHERE id = '" . $r['id'] . "'");
或者,您可以SELECT
所有内容并使用unset()
在json-encoding之前清除id
列:
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']);
// whatever it is that you want to do.
}
除了最后一个用户(?)之外,不显示skills
,因为您在while
循环的每次迭代中重新分配它。以下是您可以做的事情:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = array();
while ($r = mysqli_fetch_assoc($getUsers))
{
$skills = array();
$tempRow = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']); // since you don't want the `id`.
$skills[] = $r;
}
$tempRow['skills'] = $skills;
$rows[] = $tempRow;
}
print(json_encode($rows));
希望有助于:)