【问题标题】:Dealing with "random" POST data处理“随机”的 POST 数据
【发布时间】:2013-12-15 10:59:53
【问题描述】:

我有一个从表中随机抽取 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($_POST['bills'] as $bill)改成foreach($_POST['bills'] as $key =&gt; $bill),$key就是数组中item的key(数字)。
  • 阅读 PHP 文档可以立即回答这个问题,而不会浪费时间来编写它:php.net/manual/en/control-structures.foreach.php

标签: php arrays loops key


【解决方案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
....

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多