2016-09-15 74 views
0

其實我使用PHP框架Codeigniter,我想比較從第一個foreach到第二個的值,但是出現錯誤。例如這裏:Foreach in foreach [PHP]

<?php foreach($posts->result() as $post): ?> 

    (html content) 

    <?php foreach($tags->result() as $tag) { 
     if($tag->id_users == $post->id_users) echo $tag->tag_name; 
    } ?> 

    (html content) 

<?php endforeach; ?> 

當我比較$post->id_users內第二foreach我得到的錯誤,我怎麼能解決這個問題?

+1

內如果塊後,再添加一個封閉的大括號。 – Tpojka

+0

好的,你得到一個錯誤 - 但是那個錯誤到底是什麼?你需要把它包含在你的問題中。 – Qirel

+0

您不應該混合使用正常語法和替代語法。使用一個或另一個。使用這兩者都會使您的代碼難以閱讀。 – Mike

回答

0

您不關閉第二個foreach。對於如

<?php foreach($posts->result() as $post): ?> foreach1 

    (...some html) 

    <?php foreach($tags->result() as $tag) { if($tag->id_users == $post->id_users) echo $tag->tag_name; } ?> //foreach2 

     (...some html) 

    <?php endforeach; ?> 

<?php endforeach; ?> 
0

你不應該使用$posts->result()$tags->result() foreach循環中。因爲每當foreach活着的時候它都會檢查。總體而言,它會降低腳本的性能。

<?php 
$posts = $posts->result(); 
$tags = $tags->result(); 

foreach($posts as $post) { 
?> 
    << Other HTML code goes here >> 
    <?php 
    foreach($tags as $tag) { 
     if($tag->id_users == $post->id_users) { 
      echo $tag->tag_name; 
     } 
    ?> 
     << Other HTML code >> 
    <?php 
    } 
} 
1

其更好地避免循環迴路

$tag_ids = array(); 
foreach($tags->result() as $tag) { 
    $tag_ids[] = $tag->id_users; 
} 

foreach ($posts->result() as $key => $post) { 
    if(in_array($post->id_users, $tag_ids)) { 

    } 
}