当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to fetch data from multiple multiselect dropdowns?

问题描述:

<form action="a.php" method="post">

<select id="sel_1" name="sel[]" multiple>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

</select>

<select id="sel_2" name="sel[]" multiple>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

</select>

<input type="submit"/>

</form>

Now when i am trying to fecth the data like this

$offer = $_POST['sel'];

print_r($offer);

its displaying data like this:

Array

(

[0] => 1 // 1, 2 selected for sel_1

[1] => 2

[2] => 2 // 2, 3 selected for sel_2

[3] => 3

)

Shouldn't it come like this?

Array

(

[0] => Array(

[0] => 1

[2] => 2

)

[1] => Array(

[0] => 2

[2] => 3

)

)

I want to create string data like this(in the nxt a.php file):

for sel_1 data is created like "1, 2";

for sel_2 data is created like "2, 3";

How can i fetch the data in the above format.

I am trying this

for($i = 0; $i<count($offer) ; $i++)

{

for($j = 0; $j<count($offer[$i]); $j++)

{

$string = $tring. $offer[$i][$j];

}

}

网友答案:

Set the names sel1[] and sel2[] (different). In PHP you can use array_merge to obtain another array with the values from the first and from the second array:

$offer = array_merge($_POST['sel1'], $_POST['sel2']);

$string = '';
for($i = 0; $i < count($offer); $i++)
{
    $string .= $offer[$i];
}
网友答案:

Try like this,it's working as per your requirement:

Instead of this

$offer = $_POST['sel'];

Put like this

 $offer[] = $_POST['sel'];

Code:-

<form action="" method="POST">
    <select id="sel_1" name="sel1[]" multiple>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>

    <select id="sel_2" name="sel2[]" multiple>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    </select>
    <input type="submit"/>

    </form>
<?php
error_reporting(0);
    $offer=array();
    $offer[] = $_POST['sel1'];
    $offer[]= $_POST['sel2'];
    echo "<pre>";
    print_r($offer);
    echo "</pre>";
    ?>

For output click here: Output

网友答案:

Try this:

<form action="a.php" method="post">

<select id="sel_1" name="sel[1][]" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="sel_2" name="sel[2][]" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<input type="submit"/>

</form>

Worked for me

分享给朋友:
您可能感兴趣的文章:
随机阅读: