以下代码不会在浏览器中显示任何内容。所有数据库名称和表名称都是正确的。在while循环中添加行echo json_encode($ temp)会将结果显示为对象。
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'sample_userdata');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$stmt = $conn->prepare("SELECT questions FROM sample_questions;");
$stmt->execute();
$stmt->bind_result($post);
$userdata = array();
while($stmt->fetch()){
$temp = array();
$temp['questions'] =$post;
array_push($userdata,$temp);
}
echo json_encode($userdata);
?>
答案 0 :(得分:0)
当您使用json_decode()函数时,它将为带有键的数组创建对象
$x['test1'] = 1;
$x['test2'] = 2;
echo json_encode($x);
// Result: {"test1":1,"test2":2}
您可以使用array_values()删除键
$x['test1'] = 1;
$x['test2'] = 2;
echo json_encode(array_values($x));
// Result: [1,2]