在我的web服务器上,我不能在PHP脚本中使用get_result()
。我得到错误调用未定义的方法mysqli_stmt::get_result。
但是bind_result()
和fetch()
是有效的,但我每次都必须根据SELECT结果声明不同的列,但我希望它是通用的。
我得到的最接近的代码是:
function bind_result_array($stmt)
{
$meta = $stmt->result_metadata();
$result = array();
while ($field = $meta->fetch_field())
{
$result[$field->name] = NULL;
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
return $result;
}
function getCopy($row)
{
return array_map(create_function('$a', 'return $a;'), $row);
}
$stmt = $mysqli->prepare("SELECT 1 as userId, 2 as message UNION SELECT 3 as userId, 4 as message");
$stmt->execute();
$row = bind_result_array($stmt);
if(!$stmt->error)
{
while($stmt->fetch())
$genericArray[$row['userId']] = getCopy($row);
}
echo "{ '"userId'": ";
echo json_encode($genericArray);
echo "}";
$stmt->close();
$mysqli->close();
其输出为:
{"userId":{"1":{"userId":1,"消息":2},"3":{"userId":3,"消息":4}}}
尽管应该是:
{"userId":[{"userId":1,"消息":2},{"userId":1,"消息":2}]}
如何从json响应中获得这个附加级别,并使其成为json格式的数组?或者有没有其他方法可以在不每次更改代码的情况下以json格式获得SELECT结果。
您在以下代码中显式设置数组键:
if(!$stmt->error)
{
while($stmt->fetch())
$genericArray[$row['userId']] = getCopy($row);
}
要获得您想要的JSON输出,您需要执行以下操作:
if(!$stmt->error)
{
while($stmt->fetch())
$genericArray[] = getCopy($row);
}
如果您使用第一个片段进行重复数据消除,那么我实际上建议您在SQL中这样做。