解析数组的功能总是在返回" True"

时间:2016-09-19 01:42:05

标签: php arrays shopify

我正在为客户构建Shopify网站,我们正在使用一个应用程序(Bespoke Shipping),它允许您编写PHP代码来操作传递到函数中的变量。我使用foreach循环进行了测试,我用它来检查订单是否被运送到美国48个州的一个州。这个测试总是返回" true",当它应该只返回" true"当较低的48个州缩写的数组与其被传递到的状态不匹配时。这是我的代码:

$usr_province = $DATA['destination']['province'];

$is_lower_48 = false;
$lower_48 = array('AL', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY');

foreach ($lower_48 as $m) {
    if ($usr_province == $m) {
        $is_lower_48 = true;
    }
}

if (($DATA['destination']['country'] == 'US') && ($is_lower_48 == true)) {
    /* apply the rules for lower 48 U.S. shipping */
} elseif (($DATA['destination']['country'] == 'US') && ($is_lower_48 == false))  { /* If the destination country is in the US and NOT in the lower 48 states */
    /* apply the rules for non-contiguous U.S. shipping */
}

1 个答案:

答案 0 :(得分:1)

使用in_array(在数组中)函数来检查数组中的值

$usr_province = $DATA['destination']['province'];

$is_lower_48 = false;
$lower_48 = array('AL', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY');

if(in_array($usr_province, $lower_48)) {
    $is_lower_48 = true;
}


if (($DATA['destination']['country'] == 'US') && ($is_lower_48 == true)) {
    /* apply the rules for lower 48 U.S. shipping */
} elseif (($DATA['destination']['country'] == 'US') && ($is_lower_48 == false))  { /* If the destination country is in the US and NOT in the lower 48 states */
    /* apply the rules for non-contiguous U.S. shipping */
}