避免在数组中重复字符串

时间:2015-01-16 03:41:09

标签: php wordpress

$events = get_posts(array('post_type' => 'event','post_status' => 'publish'));
        if ( $events ) :
        echo '<ul class="event-months">';
            foreach ( $events as $event ) {
                $metabox = get_post_meta( $event->ID, 'event_options', true );
                $month = isset($metabox['start_month']) ? $metabox['start_month'] : '';

                var_dump($month);

                  echo '<li><a href="" title="">' . $month . '</a></li>';
            }
    echo '</ul>';
        endif;

打印出来:

string 'January' (length=7)
string 'February' (length=8)
string 'January' (length=7)

但我希望它像这样打印:

string 'January' (length=7)
string 'February' (length=8)

应该避免重复的字符串。

3 个答案:

答案 0 :(得分:1)

请试试这个,

$events = get_posts(array('post_type' => 'event','post_status' => 'publish'));
    if ( $events ) :
    echo '<ul class="event-months">';
        foreach ( $events as $event ) {
            $metabox = get_post_meta( $event->ID, 'event_options', true );
            $month[] = isset($metabox['start_month']) ? $metabox['start_month'] : '';
        }

        $unique_month = array_unique($month);

        foreach ($unique_month as $month)
        {
            var_dump($month);
            echo '<li><a href="" title="">' . $month . '</a></li>';
        }

    echo '</ul>';
    endif;

答案 1 :(得分:0)

我不知道php,但也许伪代码可以提供帮助:

for each event in events
   for each test_event in events
       var cnt = 0
       if event == test_event then cnt++
   next
   if cnt > 1 (you should always match once)
       break/skip
   else
       display
   end if
 next

基本上,在执行任何操作之前先放置一个嵌套循环来检查事件是否重复。

答案 2 :(得分:0)

$events = get_posts(array('post_type' => 'event','post_status' => 'publish'));
$events=array_unique($events);