多个选择输入的数组

时间:2014-01-24 11:56:35

标签: php arrays forms select option

我有这样的表格:

<form>
    <select name="data[][]" multiple="multiple">
        <option>1</option>
        <option selected="selected">2</option>
    </select>

    <select name="data[][]" multiple="multiple">
        <option selected="selected">3</option>
        <option>4</option>
    </select>

    <select name="data[][]" multiple="multiple">
        <option selected="selected">5</option>
        <option selected="selected">6</option>
    </select>
</form>

我想得到这个:

$_POST['data'] = array(
    0 => array(2),
    1 => array(3),
    2 => array(5,6)
);

我反而得到了这个:

$_POST['data'] = array(
    0 => array(2),
    1 => array(3),
    2 => array(5),
    3 => array(6)
);

解决方案是设置索引:name =“data [0] []”但我想让它自动完成..

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

You don't need to insert the keys manually.
I tested your code and it seems to be correct for what you intend to get or you  expect.
I tested it like this;
<html>
<body>
<?php
if (!isset($_GET["submit"])) {
?>
<form method="get" action="yourfilename.php">
<select name="data[][]" multiple="multiple">
    <option>1</option>
    <option selected="selected">2</option>
</select>

<select name="data[][]" multiple="multiple">
    <option selected="selected">3</option>
    <option>4</option>
</select>

<select name="data[][]" multiple="multiple">
    <option selected="selected">5</option>
    <option selected="selected">6</option>
</select>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
else {
$data= $_GET["data"];
print_r($data);
echo $show;
}

\\ So to get the 5 or 6 value in the array with key "2";
\\ Output: 5
$show= $data[2][0];

\\ Or
\\ Output: 6
$show= $data[2][1];

?>
</body>
</html>

答案 1 :(得分:0)

单向。改为:

<select name="data[0][]" multiple="multiple"> 
 ...
<select name="data[1][]" multiple="multiple">
 ...
<select name="data[2][]" multiple="multiple">

另见@CBroe评论。