避免数组中的重复字符串
Avoid duplicate string in array
$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)
应避免重复字符串。
我不知道 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
基本上,在执行任何检查事件是否重复之前放置一个嵌套循环。
请试试这个,
$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;
$events = get_posts(array('post_type' => 'event','post_status' => 'publish'));
$events=array_unique($events);
$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)
应避免重复字符串。
我不知道 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
基本上,在执行任何检查事件是否重复之前放置一个嵌套循环。
请试试这个,
$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;
$events = get_posts(array('post_type' => 'event','post_status' => 'publish'));
$events=array_unique($events);