处理“随机”POST数据

时间:2013-12-15 10:59:54

标签: php arrays loops key

我有一个页面从表中提取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。

2 个答案:

答案 0 :(得分:1)

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
....

答案 1 :(得分:0)

您可以使用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"; 
}