使用两个键从SQL创建多维数组

时间:2022-09-08 12:19:45

My SQL table is structured like this: class_id, class_name, day

我的SQL表结构如下:class_id,class_name,day

I want to convert this into a multidimensional array structured as below

我想将其转换为多维数组,结构如下

$days['day']['class_id']

$天[ '天'] [ '类标识码']

My attempt so far is as follows:

我到目前为止的尝试如下:

while ($row = mysqli_fetch_assoc($result)) {
    $days[$row['day']] = $row;
}

This creates a second layer to the array based on the day, however I'm not sure how to develop that further to sort the rows based on class_id.

这会根据当天为数组创建第二层,但是我不确定如何进一步开发基于class_id对行进行排序。

I then want to echo each row out based on the day using the id as the key using a foreach loop. This is what I have so far.

然后,我希望使用foreach循环使用id作为键,根据当天回显每一行。这就是我到目前为止所拥有的。

   foreach ($days['Monday'] as $id => $value) {

         echo "<div class='class'>";
         echo $value['class_name'];
         echo "</div>";

Any help would be massively helpful!

任何帮助都会非常有帮助!

1 个解决方案

#1


1  

while ($row = mysqli_fetch_assoc($result)) {
    $days[$row['day']][$row['class_id']] = $row;
}

and then use it in foreach like you wrote.

然后像你写的那样在foreach中使用它。

#1


1  

while ($row = mysqli_fetch_assoc($result)) {
    $days[$row['day']][$row['class_id']] = $row;
}

and then use it in foreach like you wrote.

然后像你写的那样在foreach中使用它。