如何将 Arrays 内部指针设置为特定位置?PHP/XML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/795625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:52:44  来源:igfitidea点击:

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

phpxmlarrays

提问by chris

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

我正在尝试使用 XML 而不是数据库来构建一个小站点。

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

我想构建一个下一个和上一个按钮,它将相对于我显示的内容起作用。

I found the php function next() and prev() as well as current() but I do not know how to set the pointer to a specific position to be able to navigate relative to the current page.

我找到了 php 函数 next() 和 prev() 以及 current() 但我不知道如何将指针设置为特定位置以便能够相对于当前页面进行导航。

$list=array('page1','page2','page3')

eg if im displaying contents of page2 how could I tell php i am at $list[1] so that next($list) shows page3?

例如,如果我显示 page2 的内容,我怎么能告诉 php 我在 $list[1] 以便 next($list) 显示 page3?

Thanks in advance

提前致谢

采纳答案by matpie

If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:

如果您的数组始终索引一致(例如,'page1' 始终位于索引 '0'),则相当简单:

$List = array('page1', 'page2', 'page3', 'page4', 'page5');
$CurrentPage = 3; // 'page4'

while (key($List) !== $CurrentPage) next($List); // Advance until there's a match

I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:

我个人不依赖自动索引,因为自动索引总是有可能改变的。您应该考虑明确定义键:

$List = array(
    '1' => 'page1',
    '2' => 'page2',
    '3' => 'page3',
);

EDIT:If you want to test the values of the array (instead of the keys), use current():

编辑:如果要测试数组的值(而不是键),请使用current()

while (current($List) !== $CurrentPage) next($List);

回答by Andrei Krivoshei

Using the functions below, you can get the nextand previousvaluesof the array. If current valueis not valid or it is the last(first- for prev) valuein the array, then:

使用下面的函数,您可以获得数组的下一个上一个。如果当前无效或它是数组中的最后一个第一个- 为 prev,则:

  • the function getNextVal(...)returns the first element value
  • the function getPrevVal(...)returns the last element value
  • 函数getNextVal(...)返回第一个元素值
  • 函数getPrevVal(...)返回最后一个元素值

The functions are cyclic.

函数是循环的。

function getNextVal(&$array, $curr_val)
{
    $next = 0;
    reset($array);

    do
    {
        $tmp_val = current($array);
        $res = next($array);
    } while ( ($tmp_val != $curr_val) && $res );

    if( $res )
    {
        $next = current($array);
    }

    return $next;
}

function getPrevVal(&$array, $curr_val)
{
    end($array);
    $prev = current($array);

    do
    {
        $tmp_val = current($array);
        $res = prev($array);
    } while ( ($tmp_val != $curr_val) && $res );

    if( $res )
    {
        $prev = current($array);
    }

    return $prev;
}

回答by Andrei Krivoshei

Using the functions below, you can get the nextand previousKEYsof the array. If current keyis not valid or it is the last(first- for prev) keyin the array, then:

使用下面的函数,您可以获取数组的下一个上一个KEY。如果当前无效或者它是数组中的最后一个第一个- 为 prev,则:

  • the function getNext(...)returns 0 (the first element key)
  • the function getPrev(...)returns the keyof the last array element
  • 函数getNext(...)返回 0(第一个元素
  • 函数getPrev(...)返回最后一个数组元素 的

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;
}

回答by JW.

The internal array pointer is mainly used for looping over an array within one PHP script. I wouldn't recommend using it for moving from page to page.

内部数组指针主要用于在一个 PHP 脚本中循环遍历数组。我不建议使用它从页面移动到页面。

For that, just keep track of the page number and the page size (number of items per page). Then, when you're loading another page, you can use them to decide which array items to show. For example:

为此,只需跟踪页码和页面大小(每页的项目数)。然后,当您加载另一个页面时,您可以使用它们来决定要显示哪些数组项。例如:

$pageNum = $_GET["pageNum"];
$pageSize = 10;
$startIndex = ($pageNum - 1) * $pageSize;
$endIndex = ($startIndex + $pageSize) - 1;

(or something similar)

(或类似的东西)

回答by tjungcl

another aproach without loops or search.

另一种没有循环或搜索的方法。

list($prev,$next) = getPrevNext($oObjects,$sCurrentKey);

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
    return array($prev,$next);
}

回答by EThaizone Jo

I use this code for set internal pointer with key of array.

我使用此代码设置带有数组键的内部指针。

reset($List);
while (key($List) !== $id && key($List) !== null) next($List);
if(key($List) === null) end($List);

After that you can use prev() or next().

之后,您可以使用 prev() 或 next()。

Update follow notice from @VaclavSir

更新遵循@VaclavSir 的通知

回答by Burhan Ibrahimi

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 => 

回答by Bla? Ora?em

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

这是完整的@tjunglc 循环方法:

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 :)

哦,谢谢@tjunglc :)