我正在尝试比较两个用户的图书库。我正在显示另一个用户的库,如果当前用户的库中也有该书,我希望在该书下有一个指向"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本书的用户,其中一本与另一个用户图书馆中的书相匹配,这将显示7次"somethingelse",然后显示一次"Ping"链接。我想知道是否有办法浏览8个isbn,看看其中一个匹配,然后显示"Ping"链接。我试着去掉其他{echo"something gelse";}行。然后它只显示匹配书籍的"Ping"。然而,我希望能够在那些不匹配的书下面放一些其他的东西,而不是把它们留空。非常感谢。
我无法理解您的全部代码。但我已经对我认为需要明显修改的地方进行了更改。试试看。
<?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; ?>