简体   繁体   English

每个foreach回声一次

[英]Echo once per foreach

So I have the following code: 所以我有以下代码:

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

Basically this code at the moment grabs the hex value and percentage of colours than image contains and adds them to an array. 基本上,此代码此时抓取十六进制值和颜色百分比比图像包含并将它们添加到数组中。 The code above looks to see if the hex is a certain value and the percent above 5% and if it is then it displays the success message. 上面的代码查看十六进制是否是某个值,百分比是否超过5%,如果是,则显示成功消息。 This part works exactly as it should do! 这部分完全按照应有的方式工作!

Now, what I also want is that if the colour isn't correct, so for all other hex values in the array other than $hex == 'e6af23' I want it to display a failure message but only display it once and not for every time the hex isn't that value. 现在,我还想要的是,如果颜色不正确,那么对于除$ hex =='e6af23'以外的数组中的所有其他十六进制值,我希望它显示失败消息但只显示一次而不是每次十六进制不是那个值。

Basically I need it so that the failure message is only displayed once and not 5 times (the number of hex colours in the image). 基本上我需要它,以便失败消息只显示一次而不是5次(图像中的十六进制颜色数)。

You can use a flag to indicate if the message has been outputted or not, and if so then don't output again: 您可以使用标志来指示消息是否已输出,如果是,则不再输出:

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

Just keep a list of colors you already echoed. 只需保留已经回显的颜色列表。

$failed = array();

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

Using NewFurnitureRay's answer as a guideline I came up with this answer: 使用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"; }

Seems to work now as it should only displaying either a success or a failure regardless of the success's position in the array :) 似乎现在工作,因为它应该只显示成功或失败,无论成功在阵列中的位置:)

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

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