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

前端 未结 8 1445
花落未央
花落未央 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:58

    Here's the complete @tjunglc 's approach with looping:

    protected function getPrevNext($aArray,$key)
    {
        $aKeys = array_keys($aArray); //every element of aKeys is obviously unique
        $aIndices = array_flip($aKeys); //so array can be flipped without risk
        $i = $aIndices[$key]; //index of key in aKeys
        if ($i > 0) $prev = $aArray[$aKeys[$i-1]]; //use previous key in aArray
        if ($i < count($aKeys)-1) $next = $aArray[$aKeys[$i+1]]; //use next key in aArray
        if (!isset($prev)) $prev = end($aArray);
        if (!isset($next)) $next = reset($aArray);
        return array($prev,$next);
    }
    

    Oh and thankx @tjunglc for this :)

    0 讨论(0)
  • 2020-12-01 02:11

    Try this

     public function getNextVal(&$array, $curr_val){
    
        foreach($array as $k=>$v){
            if($v['your_key'] == $curr_val){
                if(isset($array[$k+1]))
                    return $array[$k+1];
                else
                    return $array[0];
            }
        }
    
    }
    
    public function getPrevVal(&$array, $curr_val){
    
        foreach($array as $k=>$v){
            if($v['your_key'] == $curr_val){
                if(isset($array[$k-1]))
                    return $array[$k-1];
                else
                    return end($array);
            }
        }
    }
    

    for array like this:

    array (size=3)
    0 => 
    array (size=11)
      'id' => string '21' (length=2)
      'cat' => string '1' (length=1)
      'gal' => string '1' (length=1)
      'type' => string 'image' (length=5)
      'name' => string 'chalk_art_dies-irea_2nd_pic' (length=27)
      'permalink' => string 'chalk-art-dies-irea-2nd-pic' (length=27)
      'url' => string 'rxNsPoEiJboJQ32.jpg' (length=19)
      'content' => string '' (length=0)
      'date' => string '1432076359' (length=10)
      'order' => string '20' (length=2)
      'views' => string '0' (length=1)
     1 => 
       array (size=11)
      'id' => string '10' (length=2)
      'cat' => string '1' (length=1)
      'gal' => string '1' (length=1)
      'type' => string 'image' (length=5)
      'name' => string '3dchalkart' (length=10)
      'permalink' => string '3dchalkart' (length=10)
      'url' => string 's57i5DKueUEI4lu.jpg' (length=19)
      'content' => string '' (length=0)
      'date' => string '1432076358' (length=10)
      'order' => string '9' (length=1)
      'views' => string '0' (length=1)
      2 => 
    
    0 讨论(0)
提交回复
热议问题