How to set an Arrays internal pointer to a specific position? PHP/XML

前端 未结 8 1461
花落未央
花落未央 2020-12-01 01:16

Im trying to build a little site using XML instead of a database.

I would like to build a next and prev button which will work relative to the content I have displa

8条回答
  •  隐瞒了意图╮
    2020-12-01 01:51

    Using the functions below, you can get the next and previous KEYs of the array. If current key is not valid or it is the last (first - for prev) key in the array, then:

    • the function getNext(...) returns 0 (the first element key)
    • the function getPrev(...) returns the key of the last array element

    The functions are cyclic.

    function getNext(&$array, $curr_key)
    {
        $next = 0;
        reset($array);
    
        do
        {
            $tmp_key = key($array);
            $res = next($array);
        } while ( ($tmp_key != $curr_key) && $res );
    
        if( $res )
        {
            $next = key($array);
        }
    
        return $next;
    }
    
    function getPrev(&$array, $curr_key)
    {
        end($array);
        $prev = key($array);
    
        do
        {
            $tmp_key = key($array);
            $res = prev($array);
        } while ( ($tmp_key != $curr_key) && $res );
    
        if( $res )
        {
            $prev = key($array);
        }
    
        return $prev;
    }
    

提交回复
热议问题