0

我正在尝试比较两个用户的图书库。我正在显示另一个用户的图书馆,如果当前用户在他的图书馆中也有那本书,我希望在该书下有一个指向“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();    
}

这是相关的查看代码:

<?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”。但是,我希望能够在那些不匹配的书籍下放置其他内容,而不是仅仅将它们留空。谢谢!

4

1 回答 1

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; ?>
于 2013-02-25T22:39:52.447 回答