PHP多维数组重复输出

时间:2015-04-27 15:06:51

标签: php arrays multidimensional-array

以下代码循环显示用户提交数据的一系列要求(在这种情况下来自注册表单)并输出重复的错误消息。如何阻止重复的消息?

if(!empty($_POST)){
$validate = array(
    'username' => array(
            'required' => true,
            'min' => 3,
            'max' => 20,
            'unique' => 'users'
    ),
    'password' => array(
            'required' => true,
            'min' => 6
    ),
    'password_confirm' => array(
            'required' => true,
            'matches' => 'password'
    )
);

foreach($validate as $item => $rules) 
{
    foreach($rules as $rule => $rule_value) 
    {
        $value = $_POST[$item];
        $item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);

        if($rule === 'required' && empty($value))
        {
            $errors[] = "{$item} is required <br>";
        } 
    }

    if(!empty($errors))
    {
        foreach($errors as $error)
        {
            echo $error;
        }
    }
    else 
    {
        echo 'Registration Successful <br>';
    }
}}

输出:

  

需要用户名
  用户名是必需的   需要密码
  用户名是必需的   需要密码
  密码确认是必需的

1 个答案:

答案 0 :(得分:2)

你的循环有点混乱了。

foreach($validate as $item => $rules) 
{
    foreach($rules as $rule => $rule_value) 
    {
        $value = $_POST[$item];
        $item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);

        if($rule === 'required' && empty($value))
        {
            $errors[] = "{$item} is required <br>";
        } 
    }
}

// This piece that prints out the errors (if they are present) needs
// to be moved outside the loop that creates the error array.
if(!empty($errors))
{
    foreach($errors as $error)
    {
        echo $error;
    }
}
else 
{
    echo 'Registration Successful <br>';
}

另外,也许您为了提出问题而简化了这段代码,但是如果这就是全部,那么为什么不在您找到错误时打印错误而不是将其附加到错误数组?这样你只需要循环一次。您可以使用布尔值来查看是否存在错误。

$has_errors = false;
foreach($validate as $item => $rules) 
{
    foreach($rules as $rule => $rule_value) 
    {
        $value = $_POST[$item];
        $item = htmlentities($item, ENT_QUOTES, 'UTF-8', false);

        if($rule === 'required' && empty($value))
        {
            $has_errors = true;
            echo "{$item} is required <br>";
        } 
    }
}
if (!$has_errors) echo 'Registration Successful <br>';