I have a very simple form on my website.
I run this PHP to loop the form contents:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
$i = 0;
foreach($_POST as $key => $value)
{
$i ;
echo $value[$i]['row_id'];
}
I get the below:
array(1) {
["data"]=> array(2) {
[1]=> array(2) {
["row_id"]=> string(5) "33714"
["sport"]=> string(8) "swimming"
}
[2]=> array(2) {
["row_id"]=> string(5) "33715"
["sport"]=> string(8) "football"
}
}
}
33714
My PHP only echoes the first row id 33714
instead of both rows.
I feel I'm missing something obvious here.
CodePudding user response:
You're looping over the wrong thing and you're simultaneously using two different methods to loop over the same thing.
- You set
$i
to0
- Your
foreach
loop reaches$_POST['data']
- You change
$i
to1
- You access
$_POST['data'][1]
- You get to the end of the loop
You need to loop over what you actually want to loop over.
data
is a fixed thing, so hard code that. Then loop over the array it contains.
Only use a $i
variable if you are using a regular for
loop.
When you use foreach
you use the variable(s) you define inside it (in this case $key
and $value
).
foreach($_POST['data'] as $key => $value) {
echo $value['row_id']
}
CodePudding user response:
Simply put, you need to loop the items of $_POST['data']
instead of just $_POST
echo '<pre>';
var_dump($_POST);
echo '</pre>';
foreach($_POST['data'] as $key => $item)
{
echo $key.':'. $item['row_id'];
}