繁体   English   中英

如何将多维数组转换为mysql表

[英]How to convert a multidimensional array into a mysql table

我有以下代码以多维数组的形式创建修订时间表。 每个部分代表每天要修改的时间,每个小时代表要修改的时间。我试图将这个多维数组转换为mysql中的表,以便该时间表对用户友好并且可以保存等等。 这是用于生成时间表以及生成的时间表的代码。

<?php
if(!isset($_POST['subjects'])) {
    header('Location: index.php');
}
define('DAY_LENGTH', 12);
$timetable = [];
foreach ($_POST as $subject => $n) {  // add in the required amount of subjects
    $timetable = array_merge($timetable, array_fill(0, $n, $subject));
}
$timetable = array_merge($timetable, array_fill(0, DAY_LENGTH * 7 - count($timetable), ''));  // fill the array with empty values
shuffle($timetable);  // shuffle the set
$timetable = array_chunk($timetable, DAY_LENGTH);  // split it into 7 days

echo '<pre>';
var_dump($timetable);
echo '</pre>';

这是数组结构,它可以用于7个子数组,但是我只显示了前2个以节省时间。 每个子数组代表一周中的某一天,即[0]将是星期一,而其中的每个数组则是一天中的时间,然后是一个主题,即[8] = 8pm和物理

    array(7) {
  [0]=>
  array(12) {
    [0]=>
    string(0) ""
    [1]=>
    string(9) "Computing"
    [2]=>
    string(7) "Physics"
    [3]=>
    string(7) "Physics"
    [4]=>
    string(7) "Physics"
    [5]=>
    string(5) "Maths"
    [6]=>
    string(7) "Physics"
    [7]=>
    string(7) "Physics"
    [8]=>
    string(7) "Physics"
    [9]=>
    string(7) "Physics"
    [10]=>
    string(7) "Physics"
    [11]=>
    string(7) "Physics"
  }
  [1]=>
  array(12) {
    [0]=>
    string(7) "Physics"
    [1]=>
    string(9) "Computing"
    [2]=>
    string(7) "Physics"
    [3]=>
    string(7) "Physics"
    [4]=>
    string(7) "Physics"
    [5]=>
    string(7) "Physics"
    [6]=>
    string(5) "Maths"
    [7]=>
    string(7) "Physics"
    [8]=>
    string(7) "Physics"
    [9]=>
    string(7) "Physics"
    [10]=>
    string(7) "Physics"
    [11]=>
    string(5) "Maths"
  }

通过双循环,您可以访问所需的参数。

例如:

foreach ($timetable as $day => $subTimetable) {
    foreach ($subTimetable as $hour => $subject) {
        $sql = "INSERT INTO `table` (`day`, `hour`, `subject`) VALUES (:day, :hour, :subject);";
        $values = array(
            'day' => $day,
            'hour' => $hour,
            'subject' => $subject
        );
        // Execute insert here
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM