开发者

using foreach with a multi-dimensional array

开发者 https://www.devze.com 2023-03-04 03:11 出处:网络
I currently construct a multi-dim array from my input. like so: (example) <form method=post action=\"testing.php\">

I currently construct a multi-dim array from my input. like so: (example)

<form method=post action="testing.php">
<input name="response[0]['id']" type="hidden" value="<? echo $q1; ?>">
<input name="response[0]['answer']" type=text value=''>
<input name="response[1]['id']" type="hidden" value="<? echo $q2; ?>">
<input name="response[1]['answer']" type=text value=''>
<input name="response[2]['id']" type="hidden" value="<? echo $q3; ?>">
<input name="response[2]['answer']" type=text value=''>
<input name="response[3]['id']" type="hidden" value="<? echo $q4; ?>">
<input name="response[3]['answer']" type=text value=''>
<input type="submit" value="submit">
</form>

so that is successfully 开发者_如何学Cbe POSTED. However I am trying to use a foreach to print out the values and I am getting it wrong.

EDIT my output array:

Array ( 
[0] => Array 
( 
['id'] => q1 
['answer'] => 1 
) 
[1] => Array 
( 
['id'] => q2 
['answer'] => 2 
) 
[2] => Array 
( 
['id'] => q3 
['answer'] => 3 
) 
[3] => Array 
( 
['id'] => q4 
['answer'] => 4 
)
) 

can somebody explain how i would extract the values with a foreach or even a better way?

many thanks


foreach ($_POST['response'] as $response) {
  echo $response['id'];
  echo $response['answer'];
}

This should do it.


EDIT
Note the apos (') are part of the name! Either change the HTML (response[0][id]) or do the following.

The incoming array should look like:

$response = array(
    0 => array("'id'" => ..., "'answer'" => ...),
    1 => array("'id'" => ..., "'answer'" => ...),
    2 => array("'id'" => ..., "'answer'" => ...),
    3 => array("'id'" => ..., "'answer'" => ...),
);

Thus,

foreach ($response as $resp) {
    print 'ID=' . $resp["'id'"] . ', answer=' . $resp["'answer'"];
}

The problem: <input name="response[0]['answer']" /> will yield an array with 'answer' as key. I.e., the literal string with apos, not just answer. You should probably change the HTML to <input name="response[0][answer]" /> to avoid confusion. I will try and see if this is documented behavior. This behavior is indicated in the docs.


is this what you're trying to do?

<?php foreach($response as $entry): ?>
    <input name="<?php echo $entry['id']; ?>" />
    <input name="<?php echo $entry['answer']; ?>" />
<?php endforeach; ?>

and ofcourse structure the inputs the way you would as above

0

精彩评论

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