【问题标题】:Echo once per foreach每个 foreach 回显一次
【发布时间】:2012-08-15 02:50:53
【问题描述】:

所以我有以下代码:

$colors=$ex->Get_Color("images/avatarimage3.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
foreach ( $colors as $hex => $count )
{
    if ($hex == 'e6af23' && $count > 0.05) 
    { 
        echo "The image has the correct colour"; 
    } 
    else 
    { 
        echo "The image doesn't have the correct colour"; 
    }
}

目前,这段代码基本上会获取图像包含的十六进制值和颜色百分比,并将它们添加到数组中。上面的代码查看十六进制是否为某个值,百分比是否高于 5%,如果是,则显示成功消息。这部分完全按照应有的方式工作!

现在,我还想要的是,如果颜色不正确,那么对于数组中除 $hex == 'e6af23' 之外的所有其他十六进制值,我希望它显示失败消息,但只显示一次而不是每次十六进制不是那个值。

基本上我需要它,以便失败消息只显示一次而不是 5 次(图像中十六进制颜色的数量)。

【问题讨论】:

    标签: php arrays hex


    【解决方案1】:

    只需保留您已经回显的颜色列表。

    $failed = array();
    
    forech ($colors as $hex) {
        if (!in_array($hex, $failed) && $error) {
            echo 'Failed at hex ' . $hex;
            $failed[] = $hex;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用标志来指示消息是否已输出,如果是则不再输出:

      $colors=$ex->Get_Color("images/avatarimage3.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
      $error_displayed = false;
      foreach ( $colors as $hex => $count ) {
          if ($hex == 'e6af23' && $count > 0.05) {
              echo "The image has the correct colour";
          } else if (!$error_displayed) {
              echo "The image doesn't have the correct colour";
              $error_displayed = true;
          }
      }
      

      【讨论】:

      • 绝对完美!为什么我没有想到这样做。谢谢! :) 10 分钟后我会接受你的回答 :) 啊等等 - 如果它是成功的,它也会显示一次失败消息。如果颜色已经成功,有没有办法完全删除此失败消息。
      • 这样做的原因是因为它显然会循环遍历数组,而我正在寻找的十六进制并不总是第一个,因此当这是成功消息时会在成功消息前面显示失败消息案例。
      【解决方案3】:

      使用 NewFurnitureRay 的答案作为指导,我想出了这个答案:

      $colors=$ex->Get_Color("images/avatarimage.png", $num_results, $reduce_brightness, $reduce_gradients, $delta);
      $success = true;
      foreach ( $colors as $hex => $count ) {
      if ($hex !== 'e6af23') {$success = false; }
      if ($hex == 'e6af23' && $count > 0.05) {$success = true; break;}
      }
      
      if ($success) { echo "Success"; } else { echo "This is a failure"; }
      

      现在似乎可以工作了,因为无论成功在数组中的位置如何,它都应该只显示成功或失败:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        • 2016-04-18
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        相关资源
        最近更新 更多