自己制作一个链表用来存储列表信息,并查找当前id信息,找上一条信息,下一条信息(信息浏览的时候方便使用)

偶然看到某些网站在新闻详情中 ,往往是需要根据当前信息id获取到上一条信息和下一条信息的,而通常我们的做法是先获取当前信息,再获取上一条信息,再获取下一条信息,就需要发送三次查询才能够得到这些信息,一些编程网站或者论坛给出的方案是用SQL union写的。

比如当前id为5 想获取当前信息 上一条信息 下一条信息就是

(select * from news where id <5 order by id desc limit 1)
union
(select * from news where id=5 )
union
(select * from news where id >5 order by id asc limit 1)

结果如图

而如果这样写觉得不太好的话也可以写成这样

select * from news where id in (
    select id from (
        (select id from news where id >5 order by id asc limit 1)
        union
        (select 5 as id)
        union
        (select id from news where id <5 order by id desc limit 1)
    ) as tmp
) order by id asc;

结果如图

总之脱离不了用数据库进行union查询,这里我提供用程序的解决方案,就是在数据量不是很多的情况下,把所有列表信息查询出来后放入缓存,然后组成一个链表。链表的定义和使用如下:

<?php
class Chain
{
    private $chain_list=array();//链表以索引为key的总数组
    private $key_list=array();//key的集合数组
    private $current_index=0;//当前查找到的那个索引位置
    function __construct($array=array(),$index="id")
    {
        foreach($array as $value)
        {
            $key=isset($value[$index])?$value[$index]:die("链表结构没有设定索引");
            $this->chain_list[$key]=$value;
            $this->key_list[]=$key;
        }
    }
    public function find($index="")
    {
        if($index===""){return false;}
        if(isset($this->chain_list[$index]))
        {
            $this->current_index=array_search($index,$this->key_list);//找到你想要的那个索引对应的位置
        }
        return isset($this->chain_list[$index])?$this->chain_list[$index]:false;
    }
    public function prev()
    {
        //上一位
        if($this->current_index==0)
        {
            //说明现在你选择的是第一个 第一个没有上一位
            return false;
        }else
        {
            $find_key=$this->current_index-1;//索引前面的那位
            $key=$this->key_list[$find_key];//寻找总数组中的索引
            return isset($this->chain_list[$key])?$this->chain_list[$key]:false;
        }
    }
    public function next()
    {
        //下一位
        if($this->current_index==count($this->chain_list)-1)
        {
            //说明现在你选择的是最后一个 最后一个没有下一位
            return false;
        }else
        {
            $find_key=$this->current_index+1;//索引前面的那位
            $key=$this->key_list[$find_key];//寻找总数组中的索引
            return isset($this->chain_list[$key])?$this->chain_list[$key]:false;
        }
    }
}
$list=array(
    array("id"=>1,"title"=>"第1条新闻","desc"=>"第1条新闻描述"),
    array("id"=>2,"title"=>"第2条新闻","desc"=>"第2条新闻描述"),
    array("id"=>3,"title"=>"第3条新闻","desc"=>"第3条新闻描述"),
    array("id"=>4,"title"=>"第4条新闻","desc"=>"第4条新闻描述"),
    array("id"=>5,"title"=>"第5条新闻","desc"=>"第5条新闻描述"),
    array("id"=>6,"title"=>"第6条新闻","desc"=>"第6条新闻描述"),
);

$chain=new Chain($list,"id");
$id=5;
$now=$chain->find($id);//找到当前的那条
$prev=$chain->prev($id);//找到前一条
$next=$chain->next($id);//找到后一条
var_dump($prev);//打印当前的那条
var_dump($now);//打印前一条
var_dump($next);//打印后一条
var_dump($chain);//打印链表
?>

结果如图

原文地址:https://www.cnblogs.com/lizhaoyao/p/6612038.html