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

时间:2017-01-19 09:25:07

标签: php mysql arrays multidimensional-array

我有以下代码,它以多维数组的形式创建修订时间表。每个部分代表一天和每小时一个时间段进行修改。我试图将这个多维数组转换为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"
  }

1 个答案:

答案 0 :(得分:2)

使用双循环,您可以访问所需的参数。

例如:

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
    }
}