douxuanjie2692 2012-01-08 23:30
浏览 66
已采纳

在foreach中的Php elseif条件

I have this problem regarding an if/elseif condition in a foreach look. I have searched over and over and really out of ideas. So I have this array:

Array (

[0] => stdClass Object
    (
        [title] => main
        [value] => value1
    )

[1] => stdClass Object
    (
        [title] => other
        [value] => value2
    )

[2] => stdClass Object
    (
        [title] => second
        [value] => value3
    )

[3] => stdClass Object
    (
        [title] => other
        [value] => value4
    )

[4] => stdClass Object
    (
        [title] => other
        [value] => value5
    )

)

As you can see obj0 has title=>main and obj2 has title=>second, the rest of "titles" are set to other.

I have this foreach:

foreach ($objects as $object): 
    if($object->title == 'second') { 
        //this value is rarely added, so it must have a "priority" and be showed
        echo '<span></span>';
    } elseif($object->title == 'main') { 
        //i mostly want to show this, but not if $object->title has the value 'second'.
        echo '<div></div>';
    }
endforeach;

This loop returnes both "span" and "div" which i don't want. I can't manage to show only title=>"second" (if it's there), and title=>"main" only if "second" doesn't exist. So either display spans, either div's.

Hope i explained good, if not i apologize! Thank you very much and i really appreciate your help!

Marius

  • 写回答

2条回答 默认 最新

  • douyiyang6317 2012-01-08 23:39
    关注

    If either may appear at any position in the array - i.e. main may appear before second (as appears to be the case) - you will have to loop the entire array before making the decision what to display:

    $main = $second = FALSE;
    foreach ($objects as $object): 
        if($object->title == 'second') { 
            $second = TRUE;
            break; // Added as @PeterKrejci pointed out
        } elseif($object->title == 'main') { 
            $main = TRUE;
        }
    endforeach;
    
    if($second) { 
        echo '<span></span>';
    } elseif($main) { 
        echo '<div></div>';
    }
    

    If second will always appear before main, all that is needed is a couple of breaks:

    foreach ($objects as $object): 
        if($object->title == 'second') { 
            echo '<span></span>';
            break;
        } elseif($object->title == 'main') { 
            echo '<div></div>';
            break;
        }
    endforeach;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等