【问题标题】:Function That Parses Array Is Always Returning "True"解析数组的函数总是返回“真”
【发布时间】:2016-09-19 01:42:05
【问题描述】:

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

$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 */
}

【问题讨论】:

  • 所以如果我没看错$is_lower_48 = true; 应该只在$usr_province 不在数组$lower_48 中时出现,对吗?
  • 不要循环:if(in_array($usr_province,$lower_48)),如果需要调整大小写
  • Memor-X - 正好相反。如果 $lower_48 数组包含 $usr_province,则 $is_lower_48 应设置为 true。
  • 失败的测试数据是什么?
  • samgak- 有点奇怪。基本上,Shopify 中有一个自定义运输选项,适用于我正在使用的应用程序。如果较低 48 的测试数据失败并且该国家/地区仍然是美国,则它应该显示在该自定义运输选项中。我知道它每次都评估为“真”,因为当我翻转 if 语句时,代码会出现在运输区域。

标签: php arrays shopify


【解决方案1】:

使用 in_array(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 */
}

【讨论】:

    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2016-07-16
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多