将数据库记录集检索到php中的数组中

2022-01-21 00:00:00 json arrays dataset php

我想从 MySQL 表中检索一组记录作为数组.

I want to retrieve a set of records from a MySQL table as an array.

到目前为止,我能够将每一行作为关联数组进行检索.但我想要一个数组中的所有行,因为我必须访问 jQuery 中的完整对象才能显示它们.

So far I was able to retrieve each row as an associative array. But I want all the rows in one array because I have to access that complete object in jQuery to display them.

这是我到目前为止所做的.这是我检索数据的 .php 脚本

This is what I have done so far.This is my .php script to retrieve data

//select query    
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());

$numRows = mysql_num_rows($result); //to iterate the for loop

//passing as an associative array

for ($count = 0; $count < $numRows; $count++){
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    echo json_encode($row);     
}

这是我目前得到的

{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"}
{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"}
{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"}
{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"} 

但我希望这个结果集如下.

But I want this result set as follows.

[
    {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
    {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
    {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

我为此寻求帮助.提前致谢.

I seek help in doing this. Thanks in advance.

推荐答案

全部放在一个数组中,然后json_encode:

Put it all in one array, then json_encode it:

$json = array( );
$result = mysql_query("SELECT * FROM student",$con) or die (mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
    $json[] = $row;
}
echo json_encode( $json );

仅供参考:无需计算要循环的结果数.mysql_fetch_* 将在内部保留一个指向当前记录的指针,并在每次调用时增加它.这使它成为在简单的 while 循环中使用的完美候选者.此外,您可以简单地使用 mysql_fetch_assoc 代替 mysql_fetch_array 和传递 MYSQL_ASSOC,这是我更喜欢的一种方法.也使代码更易于阅读(在我看来,无论如何).

FYI: there's no need to count the number of results to loop. mysql_fetch_* will internally keep a pointer to the current record and increment that on each call. That makes it a perfect candidate to use in a simple while loop. Also, instead of mysql_fetch_array and passing MYSQL_ASSOC, you can simply use mysql_fetch_assoc instead, a method I much prefer. Makes the code easier to read too (in my opinion, anyway).

相关文章