简体   繁体   中英

How to go through multiple array's and extract each value in each array using PHP?

Iam writing a program where i have a form with two fields and a 'PLUS BUTTON' upon clicking it two more fields will appear. By clicking PLUS Button again two more fields will generate and it continues as many times we click the PLUS BUTTON. Here's my program.

 <form  action="project_values/action_nowproject.php" method="post"enctype="multipart/form-data"><div id="item"><input type="text" name="add_qty"  id="add_vender" class="ttexbox" required="required"><input type="text" name="add_name" class="ttexbox"><input onClick="addRowv(this.form);" type="button"style="cursor:pointer" class="addround" /></div></form>

in Javascript

<script type="text/javascript"> var rowNum = 0; function addRowv(frm) { rowNum ++;
var row = '<p id="rowNum'+rowNum+'"><span class="ftext">Item quantity:</span>  <input type="text" name="m_name[]"  value="'+frm.add_qty.value+'"><br> <span  class="ftext">Item name: </span><input type="text" name="mi_name[]" value="'+frm.add_name.value+'"><br><br /> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRowsv').append(row); frm.add_qty.value = ''; frm.add_name.value = ''; } function removeRow(rnum) { jQuery('#rowNum'+rnum).remove(); } </script>

Now I have to fetch the values of extra fields appeared by clicking the plus button and send them to database.

How to fetch the values multiple array's genereated? heres my sql query insert statement.

$mp = "INSERT INTO  pm_manr(name,item_nm)VALUES ('$add_qty','$item_name')"; 

$updata = mysql_query($mp);

How to get values in $add_qty,$item_name ? Some one pls help me.

Lets asume you have something like this:

line 1 <input name="foo[]" />    <input name="bar[]" />
line 2 <input name="foo[]" />    <input name="bar[]" />
line Y <input name="foo[]" />    <input name="bar[]" />
line Z <input name="foo[]" />    <input name="bar[]" />

You can loop trough them both by using the key from a foreach on the other values:

foreach($_POST['foo'] as $key =>$value){
    echo $_POST['foo'][$key]; // the same as echo $value
    echo $_POST['bar'][$key]; // the corresponding value of $_POST['bar']

    // This is where you add your query
}

Use array_combine() which creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Try this:

$arr = array_combine($_POST['m_name'],$_POST['mi_name']); // combines both arrays
foreach($arr as $key => $value){
$mp = "INSERT INTO  pm_manr(name,item_nm)VALUES ('$key','$value')";
$updata = mysql_query($mp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM