更简单的方法在PHP中执行此操作

时间:2014-05-30 12:01:19

标签: php

所以我的问题是:我怎样才能更轻松地做到这一点?

 <?php
        $b = $geld->fetch(PDO::FETCH_OBJ);
        $koopkoe = '1000.00';
        $koopvarken = '750.00';
        $koopschaap = '500.00';
        $koopdekip = '400.00';
        if ($session->logged_in == TRUE) {
            if ($b->balance > $koopkoe ) {
                $koe  = '';
            } else {
                $koe = 'disabled';
            } 
            if ($b->balance > $koopvarken){
                $varken = '';
            } else {
                $varken = 'disabled'; 
            }
            if ($b->balance > $koopschaap){
                $schaap = '';
            } else {
                $schaap = 'disabled'; 
            }
            if ($b->balance > $koopdekip){
                $kip = '';
            } else {
                $kip = 'disabled'; 
            }   
        } else {
               $online = 'disabled';
            }

        ?>

我知道你可以用“案例”做点什么,但我不知道那是什么。如果有办法更容易做到这一点。我可以简单地添加另一种动物(koe varken schaap kip是动物)

〜千电子伏

4 个答案:

答案 0 :(得分:6)

也许更干净:

$animals = array(
 'koe' => 1000,
 'varken' => 750,
 'schaap' => 500, 
  'kip' => 400,
);

foreach ($animals as $animal => $value)
{
    ${animal} = $b->balance > $value ? '' : 'disabled';
}

答案 1 :(得分:3)

<?php
    $b = $geld->fetch(PDO::FETCH_OBJ);
    $arr = array(
        'koe' => '1000.00',
        'varken' => '750.00',
        'schaap' => '500.00', 
        'kip' => '400.00'
    );
    $resultantArr = array();

    if ($session->logged_in == TRUE) {
        foreach($arr as $key=>$val) {
            ${$key} = ($b->balance > $val) ? '' : 'disabled';
        }
    } else {
        $online = 'disabled';
    }

?>

答案 2 :(得分:3)

if ($b->balance > $koopkoe ) {
    $koe  = '';
} else {
    $koe = 'disabled';
} 
if ($b->balance > $koopvarken){
    $varken = '';
} else {
    $varken = 'disabled'; 
}
if ($b->balance > $koopschaap){
    $schaap = '';
} else {
    $schaap = 'disabled'; 
}
if ($b->balance > $koopdekip){
    $kip = '';
} else {
    $kip = 'disabled'; 
}   

可以写成

$koe = ($b->balance > $koopkoe) ? '' : 'disabled';
$varken = ($b->balance > $koopvarken) ? '' : 'disabled';  
$schaap = ($b->balance > $koopschaap) ? '' : 'disabled'; 
$kip = ($b->balance > $koopdekip) ? '' : 'disabled'; 

有关详细信息,请参阅Ternary Operators

答案 3 :(得分:3)

您可以随时执行类似

的操作
...
$array = ['koe' => 1000, 'varken' => 750, 'schaap' => 500, ...];
foreach( $array as $value => $name )
{
  ${$name} = 'disabled';
  if( $b->balance > $value )
  {
    ${$name} = '';
  }
}
...

然后添加到你想要的动物身上。