0

我对 PHP 不太确定,但我通常认为它就像数学一样,括号是在其他任何事情之前完成的。

我有这个:

if( !strncmp($method_id,'OPTION', 6) && ( ($method_id != 'OPTION_5') || ($method_id != 'OPTION_12') ) )
    unset( $available_methods[ $method_id ] );

其中$method_id等于OPTION_1 到 12。

如果选项 5 和 12 可用,则有效地取消设置除这两个之外的所有内容。

问题 为什么上述方法不起作用。


编辑

所以我尝试简化它,但我认为我让它更难理解。

这是一个运输循环。可用的方法是ship:REGULAR_LOCAL, ship:EXPRESS_LOCAL, ship:PLAT_LOCAL, ship:REGULAR_INT, ship:EXPRESS_INT, ship:PLAT_INT, 和FREE_SHIPPING[where LOCALis within shipping country, and INTis international]。

当订单超过 100 美元时,会FREE_SHIPPING自动启动,但我也想根据客户的来源来选择其中一个ship:EXPRESS_LOCAL或出席。ship:EXPRESS_INT

if( !strncmp($method_id,'ship:', 5) && ( ($method_id != 'ship:EXPRESS_LOCAL') || ($method_id != 'ship:EXPRESS_INT') ) )
    unset( $available_methods[ $method_id ] );

这应该只返回FREE_SHIPPING, 和 要么ship:EXPRESS_LOCAL 要么 ship:EXPRESS_INT

环形

if( isset( $available_methods['FREE_SHIPPING'] ) ) {
    foreach( $available_methods as $method_id => $method ) {
        if( !strncmp( $method_id, 'ship:', 5 ) && ( ($method_id != 'ship:EXPRESS_LOCAL') && ($method_id != 'ship:EXPRESS_INT') ) )
            unset( $available_methods[ $method_id ] );
    }
}   
return $available_methods;
4

3 回答 3

4

你有一些逻辑废话。看第二部分的 or 。如果 method_id 不是 5 或 method_id 不是 12。好吧,如果它不是 5 或 12,那么你会得到一个真实的结果。如果它是 5,你会得到“假或真”,这是真的。如果是 12,你会得到“真或假”,这是真的。所以,整个下半场总是正确的。也许你的意思是 && 而不是 || 或者你想要 == 而不是 !=。

于 2013-03-20T01:44:59.203 回答
1

通常最好对代码进行格式化以更清楚地看到它。

从:

if( !strncmp($method_id,'OPTION', 6) && ( ($method_id != 'OPTION_5') || ($method_id != 'OPTION_12') ) )

至:

if(

  !strncmp($method_id,'OPTION', 6)

  &&

  ( 
      ($method_id != 'OPTION_5')
      ||
      ($method_id != 'OPTION_12') 
  ) 

)

这部分总是正确的:

  ($method_id != 'OPTION_5')
  ||
  ($method_id != 'OPTION_12') 

因为其中之一将永远是真实的,并且true || false === false || true === true

所以if将是真的 iff !strncmp($method_id,'OPTION', 6) === true,意思strncmp($method_id,'OPTION', 6)===false

检查您要用于它的逻辑。

于 2013-03-20T01:45:52.477 回答
0

您更新的问题应该已经包含正确的代码;这就是我写它的方式:

$localOrInt = array('ship:EXPRESS_LOCAL', 'ship:EXPRESS_INT');

if (isset($available_methods['FREE_SHIPPING'])) {
    foreach ($available_methods as $method_id => $method) {
        if (!strncmp($method_id, 'ship:', 5) && !in_array($method_id, $localOrInt)) {
            unset($available_methods[$method_id]);
        }
    }
}
于 2013-03-20T02:13:21.547 回答