SQL/PHP从表单中排序字段以进行插入


SQL/PHP sort fields from a form to make insert

我有一个表单,用户可以通过单击按钮添加新行,并自动在字段的名称上添加+1。

例如,我有我的train_id_1, train_type_1,我的用户想添加一个新的,所以现在我有train_id_2train_type_2

为了将其保存在我的数据库中,我想将sortseperate train_type_1 / train_type_2...制作foreach,然后保存在我的database中。

因此,$_POSTvar_dump看起来像:
array (size=60)
  'train_id_1' => string ' 07:36' (length=6)
  'train_type_1' => string ' -Z' (length=3)
  'user_id_1' => string 'CPN' (length=3)
  'event_criter_1' => 
    array (size=3)
      0 => string 'test' (length=4)
      1 => string '234' (length=3)
      2 => string '532' (length=3)
  'train_id_2' => string ' 08:32' (length=6)
  'train_type_2' => string ' -X' (length=3)
  'user_id_2' => string 'CPN' (length=3)
  'event_criter_2' => 
    array (size=3)
      0 => string 'TESTG' (length=5)
      1 => string 'GGG' (length=3)
      2 => string 'AETG' (length=4)
  'train_id_3' => string ' 08:36' (length=6)
  'train_type_3' => string ' -Z' (length=3)
  'user_id_3' => string 'CPN' (length=3)
  'event_criter_3' => 
    array (size=1)
      0 => string '' (length=0)
  'train_id_4' => string ' 09:04' (length=6)
  'train_type_4' => string ' -X' (length=3)
  'user_id_4' => string 'CPN' (length=3)
  'event_criter_4' => 
    array (size=1)
      0 => string '' (length=0)

你知道我怎么能使abcd_1abcd_2分离,使我的foreach(或其他解决方案)?

谢谢!

循环遍历数组,匹配_1并将发布的元素插入为一行。然后增加并匹配_2等。

$postedElements = $_POST;
$elementsPerRow = 4;
$numRows = count($postedElements)/$elementsPerRow;
// loop through the number of 'rows' to insert
for($i=1;$i<=$numRows;$i++){
     // Build an array to store matched elements to insert 
     $elementsToInsert = array();
     //process the complete _POST array each time...
     foreach($postedElements as $name => $value){
        // ...get the 'row' (the bit after the underscore)...
        //list($value,$row) = explode('_',$name); // doesn't work for 2 underscores..
        $row = end(explode($name)); // This will
        if($row == $i){
              // ...and add elements that match to an insert array
              // $elementsToInsert[] = $name; 
              $elementsToInsert[$name] = $value;
        }
    }
    // insert $elementsToInsert into DB
}

我认为,首先你需要在arraycount($arr)中有一定数量的记录。然后使用常规的for循环:

//output of field names
for ($i = 0; $i < count($arr); $i++){
    //Work with array
}

新建array

然后添加一个data from循环到新的array

我想它可以帮助你。

你为什么要对它们排序?