PHP条件设置为布尔值True或False

时间:2017-10-19 15:30:53

标签: php html boolean

我设置了以下PHP代码:

if($motherFirst == 'yes')
{$motherBool = true;}
else
{$motherBool = false;}

if($fatherFirst == 'no')
{$fatherBool = true;}
else
{$fatherBool = false;}

我已经检查过我通过做一个回声来获取$ motherFirst和$ fatherFirst的值是Yes或No。

然后我使用$ motherBool和$ fatherBool在API调用中发布boolean(true或false)而不是字符串。

然而,似乎它们被赋予类型字符串的true或false。我该怎么做才能将它们转换为布尔值?

上面已经更正,但现在有以下问题:

我也发送json如下:

 $data_string = '{
    "motherData": false,
    "fatherData": true
  }';

哪个有效,但是当我按如下方式进行时,它不起作用:

 $data_string = '{
    "motherData": '.$motherBool.',
    "fatherData": '.$fatherBool.'
  }';
你能告诉我吗?

1 个答案:

答案 0 :(得分:0)

已经回答,但这是一个简化。

$motherBool = ($motherFirst == 'yes');
$fatherBool = ($fatherFirst == 'no');

在你的第二个问题中,你回应一个bool,好像它是一个打印0或1的字符串,而不是你期望的真/假。您需要将bool转换为字符串。例如,

 $data_string = '{
    "motherData": '.($motherBool ? 'true' : 'false').',
    "fatherData": '.($fatherBool ? 'true' : 'false').'
  }';