Retrieve post array values

2020-03-23 17:55发布

问题:

I have a form that sends all the data with jQuery .serialize() In the form are four arrays qty[], etc it send the form data to a sendMail page and I want to get the posted data back out of the arrays.

I have tried:

$qty = $_POST['qty[]'];
foreach($qty as $value)
{
  $qtyOut = $value . "<br>";
}

And tried this:

for($q=0;$q<=$qty;$q++)
{
 $qtyOut = $q . "<br>";
}

Is this the correct approach?

回答1:

You have [] within your $_POST variable - these aren't required. You should use:

$qty = $_POST['qty'];

Your code would then be:

$qty = $_POST['qty'];

foreach($qty as $value) {

   $qtyOut = $value . "<br>";

}


回答2:

php automatically detects $_POST and $_GET-arrays so you can juse:

<form method="post">
    <input value="user1"  name="qty[]" type="checkbox">
    <input value="user2"  name="qty[]" type="checkbox">
    <input type="submit">
</form>

<?php
$qty = $_POST['qty'];

and $qty will by a php-Array. Now you can access it by:

if (is_array($qty))
{
  for ($i=0;$i<size($qty);$i++)
  {
    print ($qty[$i]);
  }
}
?>

if you are not sure about the format of the received data structure you can use:

print_r($_POST['qty']);

or even

print_r($_POST);

to see how it is stored.



回答3:

My version of PHP 4.4.4 throws an error: Fatal error: Call to undefined function: size()

I changed size to count and then the routine ran correctly.

<?php
$qty = $_POST['qty'];

if (is_array($qty)) {
   for ($i=0;$i<count($qty);$i++)
   {
       print ($qty[$i]);
   }
}
?>


回答4:

PHP handles nested arrays nicely

try:

foreach($_POST['qty'] as $qty){
   echo $qty
}


回答5:

I prefer foreach insted of for, because you do not need to heandle the size.

if( isset( $_POST['qty'] ) )
{
    $qty = $_POST ['qty'] ;
    if( is_array( $qty ) )
    {
        foreach ( $qty as $key => $value ) 
        {
            print( $value );
        }
    }
}