1

我打算制作一个动态复选框表单,将每个 POST 绑定到特定的按位值,并最终计算按位数字的总数。我想不出什么好的方法。谁能指导我?

<html>
<head></head>
<body>
<form method="post" action="test.php"/>
<?php

    $fields = array('writePost','readPost','deletePost','addUser',
                      'deleteUser'); 

    $perms = array(
        'writePost' => 1,
        'readPost' => 2,
        'deletePost' => 4,
        'addUser' => 8,
        'deleteUser' => 16
  );

    $results = array();



     foreach($fields as $field)
     {
          echo "<input type='checkbox' name='".$field."' value='".$field."' />";
          echo "<label for='".$field."'>".$field."</label>";
          echo "<br/>";

     }

 if(isset($_POST['submit']))
 {
     foreach($_POST as $posts)
     {
       $posts = $results;

          //
          $total_key = 0;
          $array_key = 1;

          foreach ($perms as $key)
          {

            if (!$key=='read')
              {
              $array_key = $array_key*2;
              }else{
              $array_key  = $array_key+$total_key;
            }

            foreach ($posts as $perms)
            {

              $array_key = $post;
            }

        }
    }

    var_dump($results);

}

var_dump($fields);

?>
<input type="text" name="name" value="name"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
4

1 回答 1

0

我认为您希望输入的值是数字而不是字段名称:

echo "<input type='checkbox' name='nums[]' value='".$perms[$field]."' />";

之后,您将希望从可能的最高数字开始并倒退:

$n = sizeof($perms)-1;
$total = array_sum($_POST['nums']);
for($i=$n;$i>0;$i--)
{
    $pow = pow(2, $i);
    if ($pow > $total)
    {
        //$fields[$i] is checked
        $total-=$pow;
    }
}

但实际上,如果您想要一种不那么令人困惑的方法,您可以将检查的值放入一个数组并检查它们是否在 PHP 中设置。

于 2012-12-18T19:22:50.890 回答