虽然表中没有任何记录,但如何将空数组回显到前端?
$result = mysqli_query($conn, "SELECT * FROM person");
while($res = mysqli_fetch_assoc($result)) {
$row = array(
'fname' => $res['fname']
);
$encoded[] = $row;
}
//$encoded ? echo json_encode($encoded); : echo array();
答案 0 :(得分:2)
在代码的开头初始化一个空的array
:
$encoded = array();
$result = mysqli_query($conn, "SELECT * FROM person");
while ($res = mysqli_fetch_assoc($result)) {
$encoded[] = array('fname' => $res['fname']);
}
echo json_encode($encoded);
如果未找到任何结果,则会遗漏[]
。
答案 1 :(得分:1)
将以下内容置于循环上方:
$encoded = array();
答案 2 :(得分:1)
回显空数组的最简单方法是回显一对方括号:
echo "[]";
在您的情况下,如果您已将$encoded
数组初始化到您提供的代码之上的某个位置,并且如果它未被其他代码篡改,则可以对其进行简单编码:
示例:强>
# Initialise an array.
$encoded = [];
# Execute the query.
$result = mysqli_query($conn, "SELECT * FROM person");
# Loop.
while($res = mysqli_fetch_assoc($result)) {
$encoded[]= ["fname" => $res['fname']];
}
# Echo the the array (empty or not).
echo json_encode($encoded);