PHP的get $ P $知道当前的阵列关键pvious数组元素 [英] PHP get previous array element knowing current array key

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

问题描述

我有一个特定键的数组:

I have an array with specific keys:

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

在我的应用程序知道当前键(例如 555 )。我想获得previous数组元素。在这个例子中是关键的数组元素 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.

推荐答案

一个选项:

要<一个href=\"http://stackoverflow.com/questions/795625/how-to-set-an-arrays-internal-pointer-to-a-specific-position-php-xml\">set内部指针到一定位置,你必须转发(使用 接下来 ,也许做一个 重置 之前,确保你从数组的开头开始):

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

Then you can use 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)

当然, $ P $光伏不会给你正确的价值了,但我相信你正在寻找的关键将是在数组中呢。

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的get $ P $知道当前的阵列关键pvious数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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