【问题标题】:Iteration over a object in php is not working correctly对 php 中的对象的迭代无法正常工作
【发布时间】:2014-02-19 21:53:28
【问题描述】:

我一直在努力让 php 中的对象数组的迭代工作。我有一个这样的数组结构:

Array
(

[0] => stdClass Object

(
        [tid] => 7
        [vid] => 2
        [name] => Bakkerijen
        [description] => 
        [format] => full_html
        [weight] => 0
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )

[1] => stdClass Object
    (
        [tid] => 10
        [vid] => 2
        [name] => Horeca
        [description] => 
        [format] => full_html
        [weight] => 1
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )

[2] => stdClass Object
    (
        [tid] => 8
        [vid] => 2
        [name] => Food Shops
        [description] => 
        [format] => full_html
        [weight] => 2
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )   

)

如果一个值与这个数组中的 tid 匹配,我想将一个选定的类添加到 li。

这是我为此编写的代码和 HTML:

 <?php $current_tid = 7; ?>
 <?php foreach ($terms as $term): ?>
              <?php unset($term->parents); ?> 
                <?php if($term->tid == $current_tid) { ?>
                <li><a href="/portfolio#filter=.tid-<?php print $term->tid; ?>" class="selected"><?php print $term->name;?></li>
                <?php }else if($term->tid != $current_tid){ ?>
                <li><a href="/portfolio#filter=.tid-<?php print $term->tid; ?>"><?php print $term->name; ?></a></li>

                <?php } ?>
              <?php endforeach; ?> 

这是我得到的最终输出:

<ul class="cathome-list-inner">                            
<li>
    <a class="selected" href="/portfolio#filter=.tid-7">Bakkerijen</a>
</li>
<a class="selected" href="/portfolio#filter=.tid-7"></a>
<li>
    <a class="selected" href="/portfolio#filter=.tid-7"></a>
    <a href="/portfolio#filter=.tid-10">Horeca</a>
</li>                                          
<li>
    <a href="/portfolio#filter=.tid-8">Food Shops</a></li>
<li>
    <a href="/portfolio#filter=.tid-9">Non-food Shops</a></li>
<li>
    <a href="/portfolio#filter=.tid-11">Privé interieurprojecten</a>
</li>                                                   

问题是为什么我在所选类中添加了额外的锚标记..

【问题讨论】:

    标签: php arrays object foreach


    【解决方案1】:

    在这一行:

    <li><a href="/portfolio#filter=.tid-<?php print $term->tid; ?>" class="selected"><?php print $term->name;?></li>
    

    您错过了关闭&lt;/a&gt; 浏览器可能正在尝试自动更正您的错误。

    【讨论】:

    • 谢谢伙计.. 我不敢相信我犯了这么愚蠢的错误:(
    • 发生在我们最好(和最坏)的人身上。
    猜你喜欢
    • 1970-01-01
    • 2015-07-04
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2021-03-29
    • 2015-02-02
    相关资源
    最近更新 更多