繁体   English   中英

每个foreach回声一次

[英]Echo once per foreach

所以我有以下代码:

$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次(图像中的十六进制颜色数)。

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

$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;
    }
}

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

$failed = array();

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

使用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"; }

似乎现在工作,因为它应该只显示成功或失败,无论成功在阵列中的位置:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM