我有一个数组,即$ checked_posts,看起来像 -
Array
(
[0] => 13
[1] => 15
)
此数组包含所选帖子的ID 我从数据库中获取数据,如 -
$q=mysql_query("select ID,post_title from sa_posts
where post_author='".$this->session->userdata('admin_id')."'
and post_type='post'
and post_status='publish'
order by ID desc
");
此查询获取ID和post_title
我想比较数组$ checked_posts值(id)和select查询获取id
如果两者都匹配,那么我想提前显示该记录,如果没有,则应在所有选择的记录之后显示这些记录
假设我的$ checked_post数组包含 -
Array
(
[0] => 13
[1] => 15
)
和我的选择查询获取记录(id's),如15,13,20,25,32,在这种情况下,我必须首先显示id匹配的记录,然后我想显示所有不匹配的元素。
到目前为止我已经尝试过了 -
$q=mysql_query("select ID,post_title from sa_posts
where post_author='".$this->session->userdata('admin_id')."'
and post_type='post'
and post_status='publish'
order by ID desc
");
while($p=mysql_fetch_array($q))
{
if(in_array($p['ID'],$checked_posts))
{
$check_post='checked'; // I want to display all these elements firstly and later all unmatched elements.
}
else
{
$check_post='';
}
echo "<li class='menu_post_list' id='".$m_n."' style='list-style:none;display:".$disp_post."'>
<input type='checkbox' value='".$p['ID']."' class='menu_list_post' $check_post> ".$p['post_title']."</li>";
}
请帮帮我 谢谢。
答案 0 :(得分:1)
您可以通过将检查放入查询的ORDER BY
子句来完成此操作。
$checked_str = implode(',', $checked_posts);
$q=mysql_query("select ID,post_title from sa_posts
where post_author='".$this->session->userdata('admin_id')."'
and post_type='post'
and post_status='publish'
order by ID IN ($checked_posts) DESC, ID desc
");
您还可以通过将其添加到查询结果中来避免在PHP代码中执行in_array()
测试:
$q=mysql_query("select ID,post_title, ID IN ($checked_posts) as checked
from sa_posts
where post_author='".$this->session->userdata('admin_id')."'
and post_type='post'
and post_status='publish'
order by checked DESC, ID desc
");
然后PHP代码可以使用
$check_post = $p['checked'] ? 'checked' : '';
答案 1 :(得分:1)
你可以加入已检查的ID,因为它们来自db,不需要php操作
select ID,post_title from sa_posts
JOIN someOtherTable ON sa_posts.ID=someoOtherTable.checkedIds
where post_author='".$this->session->userdata('admin_id')."'
and post_type='post'
and post_status='publish'
order by ID desc