我有一个数据库,其中包含许多条目,数据如下:
id number data
1 1 'tyfvib'
2 1 'fgdhjjd'
3 1 'gdgdhdj'
4 2 'dgfhfh'
5 2 'fghdhd'
所以我有一个唯一 ID,然后是一个包含数字的列,然后是一个包含不同字符串的列。
然后我有这样的查询:
$sql = "SELECT * FROM table";
$stmt = DB::run($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$number= $row['number'];
$data = $row['data'];
}
我想创建一个多维关联数组,它首先包含一个唯一数字数组,然后包含一个与它们关联的数据数组。
我曾尝试将 $array[$number] = $data
放入 while 循环中,但这显然只会生成一个数组,其中唯一与数字关联的数据是循环中的最后一个数据.
最佳答案
I had tried putting $array[$number] = $data inside the while loop but this obviously will just make an array where the only data associated with a number is the last one in the loop.
然后添加一组额外的[]:
$array[$number][] = $data;
每次都会在数组 $array[$number]
中创建一个新条目。
关于php - 在 PHP 中从数据库查询创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059113/