处理“;“随机”;POST数据


Dealing with "random" POST data

我有一个从表中随机抽取5行的页面。它看起来与下面的相似。

<table>
    <tr>
        <td><input type = 'radio' name='bills[1]' value = 'y'><label for='1'>Yes</label> </td>
        <td><input type = 'radio' name='bills[1]' value = 'n'><label for='1'>No</label> </td>
    </tr>
    <tr>
        <td><input type = 'radio' name='bills[8]' value = 'y'><label for='8'>Yes</label> </td>
        <td><input type = 'radio' name='bills[8]' value = 'n'><label for='8'>No</label> </td>
    </tr>
    <tr>
        <td><input type = 'radio' name='bills[2]' value = 'y'><label for='2'>Yes</label> </td>
        <td><input type = 'radio' name='bills[2]' value = 'n'><label for='2'>No</label> </td>
    </tr>
    <tr>
        <td><input type = 'radio' name='bills[6]' value = 'y'><label for='6'>Yes</label> </td>
        <td><input type = 'radio' name='bills[6]' value = 'n'><label for='6'>No</label> </td>
    </tr>
    <tr>
        <td><input type = 'radio' name='bills[3]' value = 'y'><label for='3'>Yes</label> </td>
        <td><input type = 'radio' name='bills[3]' value = 'n'><label for='3'>No</label> </td>
    </tr>
</table>

这会返回一个数组,如下所示,

Array
(
    [bills] => Array
        (
            [6] => y
            [2] => n
            [5] => n
            [1] => y
            [8] => y
        )
)

通过使用foreach($_POST['bills'] as $bill)语句,我可以循环遍历该数组,但如何获得id的值及其相应的答案?在上述情况下,为6、2、5、1、8。

foreach构造中包含密钥,如下

foreach($_POST['bills'] as $bill=>$answer)
{
echo "The value of $bill is $answer'n"; $bill will be 6,2,5,1,8 and $answer will be y,n,n,y,y
}

输出:

The value of 6 is y
The value of 2 is n
....

您可以使用key():

<?php
$array = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4
);
while($element = current($array)) {
    echo key($array)."'n";
    next($array);
}
?>

foreach($_POST['bills'] as $bill=>$answer)
{
    echo "$bill and $answer'n"; 
}