2017-02-20 62 views
0

我有两个下拉选项,具有相同的名称,如下所示。后下拉多维数组

<form action="" method="post"> 
    <select name="freeoptions[]"> 
     <option value="[7][4]">Black</option> 
     <option value="[7][5]">Blue</option> 
     <option value="[7][3]">Red</option> 
    </select> 


    <select name="freeoptions[]"> 
     <option value="[9][11]">Small</option> 
     <option value="[9][15]">Large</option> 
     <option value="[9][13]">XL</option> 
    </select> 

    <input type="submit" name="submit" value="submit"> 
</form> 

现在,当我张贴的形式,让在阵列的杆状数据,

Array 
(
    [freeoptions] => Array 
     (
      [0] => [7][4] 
      [1] => [9][11] 
     ) 
) 

但我想这个数组类似

Array 
     (
      [freeoptions] => Array 
      (
       [0] => Array 
       (
         [id] => [7] 
         [value] => [4] 
       ) 
       [1] => Array 
       (
         [id] => [9] 
         [value] => [11] 
       ) 
      ) 
     ) 

谁能帮我该怎么办这个。 谢谢,

回答

1

“value”属性中的任何内容都将作为文字字符串发送,而不管它的内容如何,​​因此您无法将值作为开箱即用的数组发布。

您可以始终将这两个值设置为相同的值属性,并将其拆分到后端。

实例HTML:

<option value="7;4"></option> 

然后做这样的事情在你的后端:

$data = []; 

// Loop all freeoptions params 
foreach ($_POST['freeoptions'] as $opt) { 
    // Split the value on or separator: ; 
    $items = explode(';', $opt); 

    if (count($items) != 2) { 
     // We didn't get two values, let's ignore it and jump to the next iteration 
     continue; 
    } 

    // Create our new structure 
    $data[] = [ 
     'id' => $items[0], // Before the ; 
     'value' => $items[1], // After the ; 
    ]; 
} 

$data -array现在应该包含您需要的数据结构。

如果你想使用$_POST -variable代替,只是简单地覆盖在foreach后的原始数据保留:

$_POST['freeoptions'] = $data; 
+0

完美,谢谢 – Hardik

0

是否要手动显示数据库结果或显示?

+0

要手动显示 – Hardik

+0

这是一个注释,不是答案 –