drxyaox153896 2012-12-18 18:51
浏览 90

关于按位运算符和foreach循环的指导

I'm planning to make a dynamic checkbox form which binds each POST to a specific bitwise value, and adventually counts the total ammount of bitwise numbers. I cant think of any good method. could anyone guide me?

<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>
  • 写回答

1条回答 默认 最新

  • dty47696 2012-12-18 19:22
    关注

    I think you want the values of your inputs to be the number instead of the field name:

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

    After than you will want to start with the highest possible number and go backwards:

    $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;
        }
    }
    

    But really, you could just put the checked values into an array and check if they are set in PHP if you want a less confusing way to do it.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分