我想选择我的表的最后4行,然后将它们放入一个JSON数组中,每个数据都附有一个数字,以便我以后可以访问它们,我会想一个循环,但不要知道如何使用计数器作为数字
获取最后四行的部分
SELECT title FROM questions ORDER BY id DESC LIMIT 4
数组就像1: data one, 2: data two...
答案 0 :(得分:1)
Aron你可以使用以下代码: -
$mysqli = new mysqli("localhost", "dbusername", "dbpassword", "sakila");
$x = 1;
$return_arr = array();
$result = $mysqli->query("SELECT title from questions ORDER By id DESC LIMIT 4");
while( $obj = $result->fetch_object() ) {
$row_array[$x] = $obj->title;
$x++;
}
$result->close();
array_push($return_arr,$row_array);
echo json_encode($return_arr);`//result [{"1":"title1","2":"title2","3":"title3}]
在循环中,我将值存储在数组($ row_array)中。这里$ x将包含数字(键)。然后将完整的结果推送到新数组中,并将结果转换为json数组。
答案 1 :(得分:0)
以下是代码的样子:
$mysqli = new mysqli('localhost', 'user', 'pass', 'database');
$stmt = $mysqli->query('SELECT title FROM questions ORDER BY id DESC LIMIT 4');
echo json_encode($stmt->fetchAll(MYSQLI_NUM));
答案 2 :(得分:0)
使用PDO检查以下代码,您也可以更改为mysqli
$dbh = new PDO('mysql:host=localhost:33060;dbname=demo', 'root', '');
$sth = $dbh->prepare("SELECT title FROM questions ORDER BY id DESC LIMIT 4");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_COLUMN);
//Key should be string, otherwise, we can not encode as json
foreach($result as $key => $value) {
$newkey = sprintf('%s',$key);
$newArray["k$newkey"] = $value;
}
echo json_encode($newArray); //result: {"k0":"title 4","k1":"title 3","k2":"title 2","k3":"title 1"}