Foreach in foreach [PHP]

时间:2016-09-15 19:21:39

标签: php codeigniter foreach

实际上我使用PHP框架Codeigniter,我想比较从第一个foreach到第二个的值,但我得到一个错误。示例:

<?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我得到错误时,我该如何解决这个问题?

3 个答案:

答案 0 :(得分: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)) {

    }
}

答案 1 :(得分: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; ?> 

答案 2 :(得分:0)

您不应在foreach循环中使用$posts->result()$tags->result()。因为它会在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
    }
}