2012-09-29 73 views
0

我想弄清楚如何检查一个对象的存在,同时做一个for循环在树枝。检查树枝中的for循环内是否存在对象

这就是我的代码的样子。

{% for topic in topics %} 
    {% set id = topic.id %} 
    {% set ratings = authRatings.id %} 

    {% if ratings is defined %} 
    {% else %} 
    {% endif %} 
{% endfor %} 

topic.id是针和authRatings是其topic_id命名的不同对象的草垛。如果一个对象匹配topic.id评级应该被定义。

object 
(stdClass)[76] 
    public '24' => 

object 
(stdClass)[77] 
     public 'topic_id' => string '24' (length=2) 
     public 'user_id' => string '2' (length=1) 
     public 'likes' => string '0' (length=1) 
     public 'dislikes' => string '1' (length=1) 
     public 'time' => string '1348927295' (length=10) 
    public '15' => 

object 
(stdClass)[78] 
     public 'topic_id' => string '15' (length=2) 
     public 'user_id' => string '2' (length=1) 
     public 'likes' => string '1' (length=1) 
     public 'dislikes' => string '0' (length=1) 
     public 'time' => string '1348927363' (length=10) 

回答

0

你可以写一个自定义函数来完成这项工作。像这样:

$twig = new Twig_Environment($loader); 
$twig->addFunction('searchRatings', new Twig_Function_Function('twig_search_ratings')); 
function twig_search_ratings($topic_id, $ratings) { 
    /* do the search in php */ 
}