中断无法正常工作


Break doesn't work properly

foreach($item_cost as $node) {
            if($node->textContent != "$0" || $node->textContent != "$0.00" || $node->textContent != "S$0" || $node->textContent != "S$0.00" ){
                $price = $node->textContent;
                break;
            }
        }

我正在尝试让它跳过 0.00 并获取找到的第一个值,例如 17.50

我仍然得到 0.00

尝试将if子句更改为以下内容:

foreach($item_cost as $node) {
  if (!in_array($node->textContent, array("$0","$0.00","S$0","S$0.00"))) {
    $price = $node->textContent;
    break;
  }
}

更易于阅读,工作更好。

如果您需要所有价格(不仅仅是第一个(,请像这样使用它:

$prices = array();
foreach($item_cost as $node) {
  if (!in_array($node->textContent, array("$0","$0.00","S$0","S$0.00"))) {
     $prices[] = $node->textContent;
  }
}

现在$prices数组包含所有非空值。

你的二元运算符应该是&&而不是||,因为$node->textContent不能等于任何给定的字符串值。

if($node->textContent != "$0" && $node->textContent != "$0.00" && $node->textContent != "S$0" && $node->textContent != "S$0.00" ){

或者,您可以考虑使用正则表达式来匹配价值为零美元的美元或新加坡元:

if (!preg_match('/^S?'$0('.00)?$/', $node->textContent)) {
    $price = $node->textContent;
    break;
}

或者,将in_array()与一组固定值一起使用以进行匹配。