douxian6260 2012-08-19 12:14
浏览 34
已采纳

每个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. 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.

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).

  • 写回答

3条回答 默认 最新

  • dsfdsf21312 2012-08-19 12:18
    关注

    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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?