PHP获取知道当前数组键的前一个数组元素 [英] PHP get previous array element knowing current array key

查看:62
本文介绍了PHP获取知道当前数组键的前一个数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有特定键的数组:

I have an array with specific keys:

array(
    420 => array(...), 
    430 => array(...), 
    555 => array(...)
)

在我的应用程序中,我知道当前密钥(例如 555).我想获得前一个数组元素.在本例中,它是键为 430 的数组元素.我怎样才能在 PHP 中做到这一点?我尝试使用 prev(),但是对于这个函数,我们应该知道当前的数组元素.没找到函数,是什么设置了当前数组元素.

In my application I know current key (for example 555). And I want to get the previous array element. In this example it is array element with key 430. How can I do this in PHP? I tried to work with prev(), but for this function we should know current array element. I didn't find function, what set the current array element.

推荐答案

一个选项:

设置指向某个位置的内部指针,你必须转发它(使用keynext,也许做一个reset 之前确保从数组的开头开始):

To set the internal pointer to a certain position, you have to forward it (using key and next, maybe do a reset before to make sure you start from the beginning of the array):

while(key($array) !== $key) next($array);

然后你可以使用prev():

$prev_val = prev($array);
// and to get the key
$prev_key = key($array);

根据您之后要对数组做什么,您可能想要重置内部指针.

Depending on what you are going to do with the array afterwards, you might want to reset the internal pointer.

如果该键不存在于数组中,则会出现无限循环,但这可以通过以下方式解决:

If the key does not exist in the array, you have an infinite loop, but this could be solved with:

 while(key($array) !== null && key($array) !== $key)

当然 prev 不会再给你正确的值,但我假设你正在搜索的键无论如何都会在数组中.

of course prev would not give you the right value anymore but I assume the key you are searching for will be in the array anyway.

这篇关于PHP获取知道当前数组键的前一个数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆