PHP中的布尔数组
我对php中的条件数组有一个疑问 这是我的密码PHP中的布尔数组,php,arrays,boolean,Php,Arrays,Boolean,我对php中的条件数组有一个疑问 这是我的密码 foreach($orders as $order) { array_push($list, array($order['name'],$order['email'],$order['buyer_accepts_marketing'])); } 现在我得到$order['buyer\u accepts\u marketing']的值是1,但我希望值为true 我试过了,但没有得到确切的答案 有人能帮我吗?提前谢谢 您可以将值强制转换为布尔值(c.
foreach($orders as $order) {
array_push($list, array($order['name'],$order['email'],$order['buyer_accepts_marketing']));
}
现在我得到$order['buyer\u accepts\u marketing']的值是1,但我希望值为true
我试过了,但没有得到确切的答案
有人能帮我吗?提前谢谢 您可以将值强制转换为布尔值(c.f.): 仅供参考,
array\u push
的快捷方式是:
foreach($orders as $order) {
$list[] = array(
$order['name'],
$order['email'],
(boolean) $order['buyer_accepts_marketing']
);
}
我通常觉得它看起来更好:)
如果要执行更复杂的逻辑来获取布尔值,可以为其创建一个新变量:
foreach($orders as $order) {
$buyer_accepts_marketing = false;
if( $order['buyer_accepts_marketing'] ) $buyer_accepts_marketing = true;
array_push($list, array(
$order['name'],
$order['email'],
$buyer_accepts_marketing
));
}
如果您想将您的买家\u accepts\u marketing
值设置为字符串值“true”或“false”,请执行以下操作:
foreach($orders as $order) {
$buyer_accepts_marketing = "false";
if( $order['buyer_accepts_marketing'] ) $buyer_accepts_marketing = "true";
array_push($list, array(
$order['name'],
$order['email'],
$buyer_accepts_marketing
));
}
请注意,字符串“true”不是布尔值,也不是“false”。例如:
if( "true" == true ) echo "It's true";
将回应“这是真的”。然而,我们也将:
if( "false" == true ) echo "It's true";
这是因为任何未设置为“0”或“
的字符串都将计算为true。您只需使用
foreach($orders as $order) {
if( $order['buyer_accepts_marketing'] ){
$buyer_accepts_marketing = "true";
}
$list[] = array(
$order['name'],
$order['email'],
$buyer_accepts_marketing;
);
}
我以前也有过类似的问题。我使用与上面提到的代码相同的代码进行了检查,但在打印数组时,此代码仍然给出值“1”。我尝试了两种代码。@Purushottamzende如何打印数组?使用“print\u r”。我还尝试将它们保存在DB中,并以字符串形式显示,但没有成功。@Purushottamzende使用var_dump打印此文件array@Purushottamzendeprint\r
似乎没有明确承认布尔值,但它实际上是一个布尔值。看这个例子:是的,我知道了。非常感谢。@railsbox:我有一个疑问,在你的回答中,$order['buyer\u accepts\u marketing']值是什么,它将显示为true,对吗?@user3667492如果$order['buyer\u accepts\u marketing']值将为0或空(null),它将不会输入条件(再次感谢!)。但是如果它是0,我将得到false。。你能帮助我吗?。
foreach($orders as $order) {
if( $order['buyer_accepts_marketing'] ){
$buyer_accepts_marketing = "true";
}
$list[] = array(
$order['name'],
$order['email'],
$buyer_accepts_marketing;
);
}