if single word already output, continue
I'm very new in PHP, and would like to do a foreach loop that won't repeat a result if the same item has been output before.
Here's my code:
foreach ( $attachments as $id => $attachment ) {
echo ($attachment->post_title);
}
As you can see, the word would be pulled by echo ($attachment->post_title);
.
Is there a way to do some checking and avoid duplicates?
Many thank开发者_开发问答s for your help.
$outputted = array();
foreach($attachments as $id => $attachment) {
if (!isset($outputted[$attachment->post_title])) {
echo $attachment->post_title;
$outputted[$attachment->post_title] = true;
}
}
You could use array_unique like Rajesh suggested and not worry with making an extra array.
foreach ( array_unique($attachments) as $id => $attachment ) {
echo ($attachment->post_title);
}
foreach ( $attachments as $id => $attachment ) {
if (!isset($outputs[$attachment->post_title])){
$outputs[$attachment->post_title] = true;
echo ($attachment->post_title);
}
}
you could do:
$output = array();
foreach ( $attachments as $id => $attachment ) {
if (!isset($output[$attachment->post_title])){
echo ($attachment->post_title);
$output[$attachment->post_title] = true;
}
}
Use associative arrays:
$used = array();
foreach ($attachments as $id => $attachment) {
if (!array_key_exists($attachment->post_title, $used)) {
$used[$attachment->post_title] = 1;
echo $attachment->post_title;
}
}
Maybe something like this?
foreach ( $attachments as $id => $attachment ) {
$attachments_posted[] = $attachment;
if (!array_search($attachment, $attachments_posted))
echo ($attachment->post_title);
}
Use an array to keep track of which titles you've already seen:
$seen = array();
foreach ($attachments as $id => $attachment) {
if (array_key_exists($attachment->post_title, $seen)) {
continue;
}
$seen[$attachment->post_title] = true;
echo $attachment->post_title;
}
精彩评论