可以迭代foreach并保持匹配值吗? (使用CodeIgniter)

时间:2013-02-25 18:51:31

标签: codeigniter foreach loops

我正在尝试比较两个用户的图书库。我正在显示另一个用户的库,如果当前用户在他的库中也有该书,我希望在该书下有一个“Ping”的链接。 以下是相关的控制器代码:

function other_user_library()
{
    $this->load->model('user_library_model');
    $this->load->model('user_information_model');
    $data['other_user_library']=$this->user_library_model->other_user_library($username);
    $data['my_book']=$this->user_library_model->compare_libraries();

    $this->load->view('other_user_library', $data);
}

以下是模型:

function other_user_library($username)
{
    $this->load->database();

    $this->db->select('*');
    //rest of query to display all of other user's books

    $query= $this->db->get();
    return $query->result();    
}
function compare_libraries()
{
    $this->load->database();

    $this->db->select('BOOK.isbn');
    //rest of query to return the current user's list of isbns in his library

    $query= $this->db->get();
    return $query->result();    
}

这是相关的View代码:

<?php foreach ($other_user_library as $row) :?>
<?php if($row->isbn)
    {
       foreach ($my_book as $thing):
       if($thing->isbn ==$row->isbn)
       {
           $ping = TRUE;
           if($ping)
           {
             echo anchor('Ping');
           } 
       }
       else
       {
          echo "somethingelse";
       }
       endforeach;  
       }?>              
   <?php endforeach;?>

现在,就目前而言,对于拥有8本书的用户,其中一本与其他用户库中的书相匹配,这将显示“somethingelse”7次,然后“Ping”链接一次。我想知道是否有办法通过8个isbns,看到其中一个匹配,然后只显示“Ping”链接。我试过删除else {echo“somethingelse”;}行。然后它只显示匹配书籍的“Ping”。但是,我希望能够在那些不匹配的书籍下放置其他东西,而不是将它们留空。谢谢!

1 个答案:

答案 0 :(得分:0)

我无法关注您的整个代码。但是我已经改变了我认为需要进行明显修改的地方。试一试。

 <?php foreach ($other_user_library as $row) : ?>
        <?php
         $ping = FALSE; //set ping here
        if ($row->isbn) {


            foreach ($my_book as $thing):
                if ($thing->isbn == $row->isbn) {
                    $ping = true;
                    break; //prevents the continuous loop after a match incase you have thousands of rows
                }

            endforeach;

            if ($ping) { //Do the echo after this point to have just one echo. You could still move out of the parent foreach loop as long as $ping is defined first.
                echo anchor('Ping');
            } else {
                echo "somethingelse";
            }
        }
        ?>              
    <?php endforeach; ?>