沃梦达 / 编程问答 / php问题 / 正文

来自表单的 POST 的 Foreach 值

Foreach value from POST from form(来自表单的 POST 的 Foreach 值)

本文介绍了来自表单的 POST 的 Foreach 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些数据从表单发布到另一个页面.这是一个购物车,提交的表单在页面上生成之前取决于购物车中有多少项目.例如,如果只有 1 个项目,那么我们只有字段名称item_name_1",它应该存储一个值,如Sticker"和item_price_1",它存储该项目的价格.但是如果有人有 5 个项目,我们将需要 'item_name_2'、'item_name_3' 等来获取每个项目的值,直到第五个.

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.

遍历这些项目以获取值的最佳方法是什么?

What would be the best way to loop through those items to get the values?

这是我所拥有的,这显然不起作用.

Here's what I have, which obviously isn't working.

extract($_POST);

$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop

while(${'item_name_' .$x} != '') {

echo ${'item_name' .$x};

$x++;

}

我对这种用法还比较陌生,所以我不完全是处理它的最佳方式.

I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.

谢谢.

推荐答案

使用类似数组的字段:

<input name="name_for_the_items[]"/>

您可以遍历字段:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

这篇关于来自表单的 POST 的 Foreach 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:来自表单的 POST 的 Foreach 值

基础教程推荐