php PHP如何遍历post数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10262763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP how to loop through a post array
提问by user1324780
I need to loop through a post array and sumbit it.
我需要遍历一个 post 数组并将其 sumbit。
#stuff 1
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
#stuff 2
<input type="text" id="stuff" name="stuff[]" />
<input type="text" id="more_stuff" name="more_stuff[]" />
But I don't know where to start.
但我不知道从哪里开始。
回答by gimg1
This is how you would do it:
这是你会怎么做:
foreach( $_POST as $stuff ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing ) {
echo $thing;
}
} else {
echo $stuff;
}
}
This looks after both variables and arrays passed in $_POST.
这会照顾传入的变量和数组$_POST。
回答by glassfish
Likely, you'll also need the values of each form element, such as the value selected from a dropdown or checkbox.
很可能,您还需要每个表单元素的值,例如从下拉列表或复选框中选择的值。
foreach( $_POST as $stuff => $val ) {
if( is_array( $stuff ) ) {
foreach( $stuff as $thing) {
echo $thing;
}
} else {
echo $stuff;
echo $val;
}
}
回答by Sarfraz
for ($i = 0; $i < count($_POST['NAME']); $i++)
{
echo $_POST['NAME'][$i];
}
Or
或者
foreach ($_POST['NAME'] as $value)
{
echo $value;
}
Replace NAMEwith element name eg stuffor more_stuff
替换NAME为元素名称,例如stuff或more_stuff
回答by Ivan Buttinoni
You can use array_walk_recursive and anonymous function, eg:
您可以使用 array_walk_recursive 和匿名函数,例如:
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits,function ($item, $key){
echo "$key holds $item <br/>\n";
});
follows this answer version:
遵循这个答案版本:
array_walk_recursive($_POST,function ($item, $key){
echo "$key holds $item <br/>\n";
});
回答by Pete
For some reason I lost my index names using the posted answers. Therefore I had to loop them like this:
出于某种原因,我使用发布的答案丢失了我的索引名称。因此我不得不像这样循环它们:
foreach($_POST as $i => $stuff) {
var_dump($i);
var_dump($stuff);
echo "<br>";
}
回答by RealSollyM
I have adapted the accepted answer and converted it into a function that can do nth arrays and to include the keys of the array.
我已经修改了接受的答案并将其转换为一个可以处理第 n 个数组并包含数组键的函数。
function LoopThrough($array) {
foreach($array as $key => $val) {
if (is_array($key))
LoopThrough($key);
else
echo "{$key} - {$val} <br>";
}
}
LoopThrough($_POST);
Hope it helps someone.
希望它可以帮助某人。

