2013-02-02 29 views
0

我想以无序列表格式显示存储在$ error中的所有错误。以下是将显示错误的代码。在PHP中以无序列表格式显示错误

<?php 
    if (!empty($error)) { 
     echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) occurred:</strong><br/>'. '<li>' . $error . '</li>' . '</p>'; 
    } elseif (!empty($success)) { 
     echo $success; 
     } 
?> 

问题是,上面的代码只显示列表中的第一个错误,但其余的只是在没有列表格式的单独行中显示。所有的错误存储在以下格式:

$error .= "You didn't type in your name. <br />"; 

我试图删除br标签,但没有奏效。

任何帮助将不胜感激。 感谢提前:)

回答

0
<?php 
    if (!empty($error)) { 
     $errors = explode('<br />', $error); 
     echo ' 
<p class="error"><strong>Your message was NOT sent<br/>The following error(s) occurred:</strong></p> 
<ul> 
'; 
     foreach($errors as $error){ 
      echo "<li>$error</li>\n"; 
     } 
     echo "</ul>"; 
    } elseif (!empty($success)) { 
     echo $success; 

    } 
?> 
+0

是的..这个很适合我...... :) 你能解释一下这个爆炸函数是如何工作的吗? – TBI

+0

@TBI它只是在换行符处拆分文本(并删除它们),并将每个片段放入一个简单的零索引数组中。 “implode”命令的对面。这两个都是非常有用的,连同'extract' – keyboardSmasher

0

你必须使用<li>每个错误,如果不是使用<br/>标签,PHP的输出应该像现在这样,

<ul> 
    <li>Error1</li> 
    <li>Error2</li> 
    <li>Error3</li> 
</ul> 

所以有这样的PHP代码,

$error .= "<li>You didn't type in your name. </li>"; 
$error .= "<li>Error2. </li>"; 
$error .= "<li>Error3 </li>"; 


echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) occurred:</strong><br/>'. '<ul>' . $error . '</ul>' . '</p>'; 
+0

我之前想过这个,但是如果我有太多的错误需要显示,这会很费时。因此,我选择了keyboardSmasher提供的答案。 – TBI

0

假设$error是一个数组(看起来如此)。

if (!empty($error)) { 
    foreach ($error as $e) { 
     printf("<li>%s</li>\n", $e); 
    } 
} 

// or just 
print "<li>". join("</li>\n<li>", $error). "</li>"; 

// extra: collecting errors 
if (trim($_POST["first_name"]) == "") { 
    $error[] = "You didn't type in your first name."; 
} 
if (trim($_POST["last_name"]) == "") { 
    $error[] = "You didn't type in your last name."; 
} 
... 
+0

不,它不是一个数组。 – TBI