PHP - 对象循环条件

时间:2017-12-29 15:11:30

标签: php loops object

我有这个对象:

$boosts = array(
    "2x12" => 500,
    "2x24" => 800,
    "2x7d" => 4500,
    "3x12" => 700,
    "3x24" => 1300,
    "3x7d" => 6500
);

然后变量:$type = "2x12"; 我想要做的是检查一个循环,如果变量$ type存在于$ boosts中。我尝试了很多代码,但我无法得到它。

foreach ($boosts as $savedTypes) {
    echo json_encode($savedTypes) . "|";
    if ($boosts[$type] === $type) {
        echo "VALID";
    }
}

2 个答案:

答案 0 :(得分:3)

除非我错过了某些内容,否则您应该能够在此例中使用array_key_exists

$boosts = array(
    "2x12" => 500,
    "2x24" => 800,
    "2x7d" => 4500,
    "3x12" => 700,
    "3x24" => 1300,
    "3x7d" => 6500
);
$type='2x12';
$valid=array_key_exists( $type, $boosts );
echo $valid ? 'VALID' : 'INVALID';

答案 1 :(得分:1)

foreach ($boosts as $key=>$value) {  
   if ($key === $type) {
    echo "VALID";
   }
 }

希望这会对你有所帮助