我需要尝试在while循环中找到字符串的第一个出现。如果我可以避免它,我宁愿不使用Jquery来找到每个元素的第一个。
while ( $teacher_assignment_query->have_posts() ) {
$teacher_assignment_query->the_post();
$assignment_fields = get_post_custom($post->ID);
//print '$assignment_fields['title'][0] and stuff here
});
这会打印出像这样的作业列表
<li class="assignments fourthgrade"><a href="#">Do worksheet 2-1</a></li>
<li class="assignments fourthgrade"><a href="#">Do worksheet 1-2</a></li>
<li class="assignments fourthgrade"><a href="#">Do worksheet 1-1</a></li>
<li class="assignments fifthgrade"><a href="#">Volunteer somewhere</a></li>
<li class="assignments fifthgrade"><a href="#">Finish science project</a></li>
他们是这样的,五年级前四年级。 $assignment_fields['grade'][0]
会为循环中的每个项打印fourthgrade
或fifthgrade
。
我有什么方法可以在它发生变化时找到,所以第一次是fourthgrade
和fifthgrade
,所以不是上面的列表,我可以这样:
<li class="heading">Fourth Grade</li> //new heading
<li class="assignments fourthgrade"><a href="#">Do worksheet 2-1</a></li>
<li class="assignments fourthgrade"><a href="#">Do worksheet 1-2</a></li>
<li class="assignments fourthgrade"><a href="#">Do worksheet 1-1</a></li>
<li class="heading">Fifth Grade</li> //new heading
<li class="assignments fifthgrade"><a href="#">Volunteer somewhere</a></li>
<li class="assignments fifthgrade"><a href="#">Finish science project</a></li>
答案 0 :(得分:2)
$last_title = '';
while ( $teacher_assignment_query->have_posts() ) {
$teacher_assignment_query->the_post();
$assignment_fields = get_post_custom($post->ID);
if($assignment_fields['grade']!=$last_title){
echo '<li class="heading">'.$assignment_fields['grade'].'</li>';
$last_title = $assignment_fields['grade'];
}
//print '$assignment_fields['title'][0] and stuff here
});
答案 1 :(得分:1)
您可以使用临时变量将当前结果与之前的结果进行比较,并在不同时更改标题 例如(元代码):
$previous_grade="";
while(conditions) {
// some code to get your data
[...]
// Compare the current grade with the previous one
$current_grade=$assignment_fields['grade'];
if($current_grade!=$previous_grade) {
print "<li class=\"heading\">$current_grade</li>";
}
// Go ahead with the list
print $assignment_fields['title'][0] and other stuffs;
// Update the temporary variable
$previous_grade=$current_grade;
}