2016-09-15 73 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)) { 

    } 
}