将复选框转换为布尔值

时间:2016-05-24 08:45:46

标签: php laravel casting comparison loose-typing

根据HTML表单的提交机制,任何复选框元素值都可能被视为“on”,“off”,1,0,“true”,“false”。

Laravel框架中是否有一个帮助程序可以将提交的FormData复选框(或普通表单)“转换”为布尔值。

我可以自己动手,但在这里要求值得一试。

以下是我要使用的内容:

<?php


function checkbox_boolean($parameter) {
    if (is_bool($parameter)) return $parameter;
    if (is_object($parameter)) return count(get_object_vars($parameter)) !== 0;
    if (is_array($parameter)) return count($parameter) !== 0;
    if (is_numeric($parameter)) { return (boolean) $parameter; }
    $p = is_string($parameter) ? strtolower($parameter) : $parameter;

    switch ($p) {
        case 'yes';
        case 'on';
        case 'true';
            return true;
            break;

        case null;
        case 'no';
        case 'off';
        case 'false';
            return false;
            break;
    }
    return false;
}

print_r([
    'yes' => [
        '"true"' => checkbox_boolean('true'),
        'true' => checkbox_boolean(true),
        '1' => checkbox_boolean(1),
        '"1"' => checkbox_boolean('1'),
        'yes' => checkbox_boolean('yes'),
        'YEs' => checkbox_boolean('YEs'),
        '<non-empty object>' => checkbox_boolean((object) [ 'z' => 'z']),
        '<non-empty array[0]>' => checkbox_boolean([0]),
    ],
    'no' => [
        '"false"' => checkbox_boolean('false'),
        'false' => checkbox_boolean(false),
        '0' => checkbox_boolean(0),
        '"0"' => checkbox_boolean('0'),
        'no' => checkbox_boolean('no'),
        'No' => checkbox_boolean('No'),
        '<empty object>' => checkbox_boolean(new stdClass),
        '<empty array []>' => checkbox_boolean([]),
    ]
]);

这个问题与“如何将字符串转换为布尔值”不重复,因为这不是一般问题。我问的是将HTML表单或者复选框元素转换为布尔值的具体过程。问题/问题的一个重要部分是确定这些复选框在由各种(常见)方法提交并由PHP解析时生成的公共值。

3 个答案:

答案 0 :(得分:2)

此答案与Laravel无关,但提供了通用的PHP解决方案。

提交表单时,将包括所有类似文本的字段,即使它们为空。其中包括type='"text",任何较新的类型,例如emaildate,以及所有未知类型,例如type="testing"

对于按钮,仅包括已选择的按钮;未选择的按钮将不存在。实际上,选定的按钮将包括0个或多个复选框,组中仅一个(如果有的话)单选按钮以及选中的提交按钮。

关于按钮的重要一点是,将发送选定的按钮,但不会发送未选定的按钮。这与按钮的实际值无关。

您可以通过测试复选框的存在来检查复选框,而不管它应该具有什么值。例如,如果您的POST表单带有

<input type="checkbox" name="ok">

您可以使用以下方法进行检查:

$ok = isset($_POST['ok']);

一些开发人员更喜欢将测试表达为:

$ok = array_key_exists($_POST,'ok');

在两种情况下,结果严格都是布尔值。

答案 1 :(得分:0)

在我的情况下,该复选框返回“ on”或“ null”,因此在控制器中,我只是执行IF语句:

run = True
while run:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
 
    # lets player move
    keys = pygame.key.get_pressed()
    
    if playerman.fall > 0 and keys[pygame.K_SPACE]:
        if keys[pygame.K_d]:
            playerman.direction = "jump1"
    else:
        if playerman.direction == "left":
            if keys[pygame.K_SPACE]:
                playerman.direction = "jump2"
 
    # direction for player animation and screen movment x
    if keys[pygame.K_d]:
        if not playerman.isJump:
            playerman.direction = "right"
    elif keys[pygame.K_a]:
        if not playerman.isJump:
            playerman.direction = "left"
    
    if playerman.direction == "right" and keys[pygame.K_SPACE]:
        playerman.direction = "jump1"
    if playerman.direction == "left" and keys[pygame.K_SPACE]:
        playerman.direction = "jump2"
 
    px, py = playerman.x, playerman.y

    # sides for player and player screen movment
    platform_rect_list = [p.rect for p in platforms]
    player_rect = playerman.get_rect()
    player_rect.topleft = (px, py)
 
    playerman.y = py
    if keys[pygame.K_d]:
        playerman.x += playerman.speed
    if keys[pygame.K_a]:
        playerman.x -= playerman.speed
    if player_rect.collidelist(platform_rect_list) > 0:
        playerman.x = px      
 
    # About isJump
    if not playerman.isJump:
        playerman.y += playerman.fall
        playerman.fall += 1
        playerman.isJump = False
 
        # this part lets you jump on platform only the top 
        collide = False
        for Platform in platforms:
            player_rect = playerman.get_rect()
            player_rect.topleft = (playerman.x, playerman.y)   
            platform_rect = Platform.get_rect()
            if playerman.get_rect().colliderect(platform_rect):
                collide = True
                playerman.isJump = False
                if platform_rect.top > playerman.x:
                    playerman.y = platform_rect.top - playerman.height
                if player_rect.right > platform_rect.left and player_rect.left < platform_rect.left:
                    playerman.x = platform_rect.left - playerman.width
                if player_rect.left < platform_rect.right and player_rect.right > platform_rect.right:
                    playerman.x = platform_rect.right
 
            # colliding with floor      
            if player_rect.bottom >= 500:
                collide = True
                playerman.isJump = False
                playerman.Jumpcount = 10
                playerman.y = 500 - playerman.height
 
        # Jumping
        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
                playerman.y -= playerman.speed
            playerman.fall = 0
 
 
    # Jump Count
 
    else:
        if playerman.JumpCount >= 0:
            playerman.y -= (playerman.JumpCount*abs(playerman.JumpCount))*0.3
            playerman.JumpCount -= 1
        else:
            playerman.isJump = False
            playerman.JumpCount = 10
 
    redrawwindow()
    if playerman.rect.colliderect(rule1.rect):
        window.blit(move,(-40,-100))
 
    pygame.display.update()

希望它可以帮助某个人。

Mário

答案 2 :(得分:0)

我的代码将复选框 name="home" 转换为 int。 如果复选框被选中 -> issert = true <=> 1 如果未选中复选框 -> issert = false <=> 0

$data = $request->all();            
$data['home'] = isset($data['home'])? 1 : 0;