开发者

Need help receiving and listing the values of an array variable after receiving it from a form

i have this in bu开发者_如何转开发y.php

<form action="cart.php">
    <?php 
    echo'<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '"  />
         <input name="variety[]" type="hidden" value="' . $variety['variety']. '"  />';
    ?>
</form>

Then to receive in cart.php I do it like

<?php
$aDoor= $_POST['price'];
$aDoor1= $_POST['variety'];
?>

$aDoor is a string and $aDoor are numbers

to sum the numbers I can easily script it inside cart.php like:

echo "Sum of vlues = ".array_sum($aDoor);

But how can I list the strings inside of $aDoor1 at the left of the prices $aDoor? and to place the sum of values script above below the $aDoor as the prices total?

Since $aDoor1 is an array i have use a foreach loop to list each item but then it will only print the word array instead of the actual values of the array variable $aDoor1

foreach($aDoor1 as $variety) {
echo '<div>'.$variety['variety']. '</div>
}

Thank you, Don't know that much of php


Even though you aren't specifying it, when you create form elements using the [] syntax after their name PHP automatically translates that into an array with auto-generated incrementing indexes (0, 1, 2, 3, etc). You can reference the array index of each of your elements as they will be matching for paired form fields:

foreach($aDoor1 as $index => $variety) {
  echo '<div>'.$aDoor[$index].': '.$variety. '</div>';
}

If you have a unique identifier for each of your varieties I would recommend manually indexing your form elements for clarity instead:

<form action="cart.php">
    <?php 
    echo'<input style="width:10px; margin-left:9px; " name="price[' . $variety['id'] . ']" type="checkbox" value="' . $variety['price']. '"  />
         <input name="variety[' . $variety['id'] . ']" type="hidden" value="' . $variety['variety']. '"  />';
    ?>
</form>

and then looping through them the same as above.


If you know that there is always one variety for every price, you can use array_combine() with the first parameter being the keys (the variety in this case) and the second being the values (the price).:

$price_list = array_combine($_POST['variety'], $_POST['price']);

Then if you want to print this out you can do:

foreach($price_list as $item => $price) {
echo "<dt>$item</dt><dd>$price</dd>"; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜