我似乎找不到从数据库结果集中形成数组的正确方法。目的是将结果数组格式化为 JSON 格式。我目前得到的只是将第一个结果放入数组中,就像这样
数组 ( [title] => 岩石 [类别] => 矿物 [id] => 39 )
当 JSON 编码时,我希望得到的是
{"title":"Rock","category":"Mineral","id":39}{"title":"Rock","category":"Music","id":40}
编码
$squery = "%rock%";
$resultArray = array();
include_once("mysqli_connect.php");
$table = "articles";
$sql = "SELECT title, category, id
FROM $table
WHERE title LIKE ?";
$stmt = mysqli_stmt_init($dbh);
if (!(mysqli_stmt_prepare($stmt, $sql))) {
echo("Write to DB failed ");
}
else { //statement prepared ok
mysqli_stmt_bind_param($stmt, 's', $squery);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $sTitle, $sCat, $sId);
while(mysqli_stmt_fetch($stmt)) {
$resultArray = ["title" => $sTitle,
"category" => $sCat,
"id" => $sId];
}
mysqli_stmt_close($stmt);
}
echo(json_encode(array_unique($resultArray)));
我已经看到 Stack 上有一些类似的问题,但他们似乎以面向对象的风格回答了这个问题,目前我只熟悉程序。