所以我有以下代码:
$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次(图像中的十六进制颜色数)。
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
只需保留已经回复的颜色列表。
$failed = array();
forech ($colors as $hex) {
if (!in_array($hex, $failed) && $error) {
echo 'Failed at hex ' . $hex;
$failed[] = $hex;
}
}
答案 2 :(得分:0)
使用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"; }
现在似乎工作,因为它应该只显示成功或失败,无论成功在阵列中的位置如何:)