我似乎找不到从数据库结果集中形成数组的正确方法。目的是将结果数组格式化为JSON格式。我目前得到的只是将第一个结果放入数组中,如此
数组([title] => Rock [category] => Mineral [id] => 39)
当JSON编码时,我想要得到的是
{ “标题”: “摇滚”, “类别”: “矿物”, “标识”:39} { “标题”: “摇滚”, “类别”: “音乐”, “标识”:40} < / p>
代码
$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上有一些类似的问题,但它们似乎以面向对象的方式回答了这个问题,目前我只熟悉程序。