从一个阵列移动命名项的编号量到另一个 [英] moving a numbered amount of named items from one array into another

查看:76
本文介绍了从一个阵列移动命名项的编号量到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全知道如何在逻辑将在这方面努力。我的脑子是油炸,我不能清晰地思考。

我处理某些POST数据,和此阵列中的其中一个字段是一个数量串。我可以读取该字符串并确定是否存在需要处理超过1小部件。

 如果($数量< = 1){// $ _ POST [WIDGET1]}

现在说有4个部件。该数量字段将反映这个数字,但我将如何通过他们循环,并将其分配到一个新的数组自己?

  $ _ POST [WIDGET1],$ _ POST [WIDGET2],$ _ POST [WIDGET3],$ _ POST [widget4]

我如何采取数量号码,用它来抓取,许多和那些特定命名项目从后阵,使用一些外卡或preFIX什么的?我不知道这是否是一个,而,或什么样的操作。我如何通过$ _ POST循环['小部件*的 X 的*'],其中X是我的数量是多少?

最终的结果是即时通讯寻求具有结构类似这样的数组:

  $部件[数据1]
$部件[数据2]
$部件[数据3]
$部件[数据4]


解决方案

使用循环,你可以访问 $ _ POST 具有可变密钥,如 $ _ POST [小部件$ I]

  $部件=阵列();
为($ i = 1; $ I< = $数量; $ I ++){
  //追加到一个数组
  $部件[] = $ _ POST [小部件$ I];
}

然而,一个更好的长期解决办法是通过添加 [] 来改变HTML表单,使得它在第一时间传递一个数组回PHP的表单输入的名称属性:

 <输入类型=文本名称='小部件[]'ID ='WIDGET1'值='WIDGET1/>
<输入类型=文本名称='小部件[]'ID ='WIDGET2'值='WIDGET2/>
<输入类型=文本名称='小部件[]'ID ='WIDGET3'值='WIDGET3/>

通过 $访问的在PHP _ POST ['部件'] ,已经是阵!

 的var_dump($ _ POST ['部件']);

I'm not exactly sure how the logic would work on this. My brain is fried and i cant think clearly.

I am handling some POST data, and one of the fields in this array is a quantity string. I can read this string and determine if there are more than 1 widgets that need handled.

if($quantity <= 1){ //$_POST[widget1] }

Now say there are 4 widgets. The quantity field would reflect this number, but how would i loop through them and assign them to a new array themselves?

$_POST[widget1], $_POST[widget2], $_POST[widget3], $_POST[widget4]

How do i take that quantity number, and use it to grab that many and those specific named items from the post array, using some kind of wild card or prefix or something? I dont know if this is a for, or while, or what kind of operation. How do I loop through $_POST['widget*X*'], where X is my quantity number?

The end result is im looking to have an array structured like this:

$widgets[data1]
$widgets[data2]
$widgets[data3]
$widgets[data4]

解决方案

Using a for loop, you can access the $_POST keys with a variable, as in $_POST["widget$i"]

$widgets = array();
for ($i=1; $i<=$quantity; $i++) {
  // Append onto an array
  $widgets[] = $_POST["widget$i"];
}

However, a better long-term solution would be to change the HTML form such that it passes an array back to PHP in the first place by adding [] to the form input's name attribute:

<input type='text' name='widgets[]' id='widget1' value='widget1' />
<input type='text' name='widgets[]' id='widget2' value='widget2' />
<input type='text' name='widgets[]' id='widget3' value='widget3' />

Accessed in PHP via $_POST['widgets'], already an array!

var_dump($_POST['widgets']);

这篇关于从一个阵列移动命名项的编号量到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆