0

我需要尝试在 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]将打印出fourthgradefifthgrade为循环中的每个项目。

有没有办法我可以找到它何时发生变化,所以第一次是fourthgradeand 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>
4

2 回答 2

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
});
于 2013-08-29T22:28:47.493 回答
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;
}
于 2013-08-29T22:30:44.720 回答