我有这段代码:
foreach($this->authors as $autor){
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
};
作者可能会重复多次。我怎么能改变这个代码,使它只打印每一个重复显示一次的代码?
提前感谢您的帮助。
答案 0 :(得分:1)
未经测试,但试试这个:
foreach(array_unique($this->authors) as $autor){
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
};
答案 1 :(得分:1)
$var = '';
foreach($this->authors as $autor){
if($var != $autor->author)
{
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
}
$var = $autor->author;
};
答案 2 :(得分:0)
最好的选择是在开始输出之前过滤数组。
如果这是不可能的,无论出于何种原因(包括个人偏好),尝试这样的事情:
$used_authors = array();
foreach($this->authors as $autor){
if(!isset($used_authors[$autor->author]){
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
$used_authors[$autor->author] = true;
}
};
答案 3 :(得分:0)
希望这会对你有所帮助
$newarray=array_unique($this->authors);
foreach($newarray as $autor){
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
}
答案 4 :(得分:0)
希望这会对你有所帮助
$unieq_array=array_unique($this->authors);
foreach($unieq_array as $autor){
if($autor->author == $filter_autor){
echo '<option value="'.$autor->author.'" selected="selected">'.$autor- >author.'</option>';
}else{
echo '<option value="'.$autor->author.'">'.$autor->author.'</option>';
}
};