2017-02-20 33 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

這是一個註釋,不是答案 –