php PHP获取知道当前数组键的前一个数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4792673/
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
PHP get previous array element knowing current array key
提问by Alex Pliutau
I have an array with specific keys:
我有一个带有特定键的数组:
array(
420 => array(...),
430 => array(...),
555 => array(...)
)
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.
在我的应用程序中,我知道当前密钥(例如555
)。我想获得前一个数组元素。在这个例子中,它是带有 key 的数组元素430
。我怎样才能在 PHP 中做到这一点?我尝试使用prev()
,但是对于这个函数,我们应该知道当前的数组元素。我没有找到函数,是什么设置了当前数组元素。
回答by Felix Kling
One option:
一种选择:
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):
要将内部指针设置到某个位置,您必须转发它(使用key
and next
,也许reset
之前做一个以确保从数组的开头开始):
while(key($array) !== $key) next($array);
Thenyou can use prev()
:
然后你可以使用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.
根据您之后要对数组执行的操作,您可能需要reset
内部指针。
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)
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.
当然prev
不会再给你正确的值,但我假设你正在搜索的键无论如何都会在数组中。
回答by Arnaud Le Blanc
Solution with fast lookups: (if you have to do this more than once)
快速查找的解决方案:(如果您必须多次执行此操作)
$keys = array_flip(array_keys($array));
$values = array_values($array);
return $values[$keys[555]-1];
array_flip
(
array_keys
($array));
will return an array mapping keys to their position in the original array, e.g. array(420 => 0, 430 => 1, 555 => 2)
.
array_flip
(
array_keys
($array));
将返回一个数组映射键到它们在原始数组中的位置,例如array(420 => 0, 430 => 1, 555 => 2)
.
And array_values
() returns an array mapping positions to values, e.g. array(0 => /* value of $array[420] */, ...)
.
And array_values
() 返回一个将位置映射到值的数组,例如array(0 => /* value of $array[420] */, ...)
.
So $values[$keys[555]-1]
effectively returns the previous elements, given that the current one has key 555.
$values[$keys[555]-1]
鉴于当前元素的键为 555,因此有效地返回了先前的元素。
Alternative solution:
替代解决方案:
$keys = array_keys($array);
return $array[$keys[array_search(555, $keys)-1]];
回答by Luca Borrione
I solved this issue in this way:
我以这种方式解决了这个问题:
function getPrevKey($key, $hash = array())
{
$keys = array_keys($hash);
$found_index = array_search($key, $keys);
if ($found_index === false || $found_index === 0)
return false;
return $keys[$found_index-1];
}
@return previous key or false if no previous key is available
@return 上一个键或 false 如果上一个键不可用
Example:
例子:
$myhash = array(
'foo' => 'foovalue',
'goo' => 'goovalue',
'moo' => 'moovalue',
'zoo' => 'zoovalue'
);
echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo
回答by cenk
@Luca Borrione's solution was helpful. If you want to find both previous and next keys, you may use the following function:
@Luca Borrione 的解决方案很有帮助。如果要同时查找上一个和下一个键,可以使用以下函数:
function getAdjascentKey( $key, $hash = array(), $increment ) {
$keys = array_keys( $hash );
$found_index = array_search( $key, $keys );
if ( $found_index === false ) {
return false;
}
$newindex = $found_index+$increment;
// returns false if no result found
return ($newindex > 0 && $newindex < sizeof($hash)) ? $keys[$newindex] : false;
}
Usage:
用法:
// previous key
getAdjascentKey( $key, $hash, -1 );
// next key
getAdjascentKey( $key, $hash, +1 );
Examples:
例子:
$myhash = array(
'foo' => 'foovalue',
'goo' => 'goovalue',
'moo' => 'moovalue',
'zoo' => 'zoovalue'
);
getAdjascentKey( 'goo', $myhash, +1 );
// moo
getAdjascentKey( 'zoo', $myhash, +1 );
// false
getAdjascentKey( 'foo', $myhash, -1 );
// false
回答by moinudin
You can iterate through the array in reverse and return the next iteration after finding the search value.
您可以反向遍历数组并在找到搜索值后返回下一次迭代。
$found = false;
foreach(array_reverse($array, true) as $key=>$value) {
if ($found) {
print "$key => $value\n";
break;
} else if ($key == 555) {
$found = true;
}
}
回答by RobertPitt
Just iterate over the array
只需遍历数组
$_index = null;
foreach($myarray as $index => $value)
{
if($key == $my_index) // if($key == 550)
{
break;
}
$_index = $index;
}
echo $_index; //the prev key from 550;
An alternative solution is to get the keys of your array within an enumerated array like so:
另一种解决方案是在枚举数组中获取数组的键,如下所示:
$keys = array_keys($my_array);
as the keys array is index you can move the the previous key like so:
由于键数组是索引,您可以像这样移动前一个键:
$required_key = (array_search(550,$keys,true) - 1);
this will fine the value of 550
, and return its index within the keys, remove one to get the previous index
这将罚款 的值550
,并在键内返回其索引,删除一个以获得前一个索引
key we have our previous key to get the value from the original array
键我们有我们以前的键来从原始数组中获取值
$value = $my_array[$required_key];
回答by O.D.
This is a simple solution for taking previous and next items, even if we are at the ends of the array.
这是一个简单的解决方案,用于获取上一个和下一个项目,即使我们位于数组的末尾。
<?php
$current_key; // the key of the item we want to search from
if (isset($array[$current_key+1]))
{
// get the next item if there is
$array_next = $array[$current_key+1];
}
else
{
// if not take the first (this means this is the end of the array)
$array_next = $array[0];
}
if (isset($array[$current_key-1]))
{
// get the previous item if there is
$array_prev = $array[$current_key-1];
}
else
{
// if not take the last item (this means this is the beginning of the array)
$array_prev = $array[count($array)-1];
}
回答by Daniel
Expanding further on the solution of Luca Borrione and cenk, so that you can wrap around the end of the array in either direction, you may use:
进一步扩展 Luca Borrione 和cenk 的解决方案,以便您可以在任一方向环绕数组的末尾,您可以使用:
function getAdjascentKey($key, $hash = array(), $increment) {
$keys = array_keys($hash);
$found_index = array_search($key, $keys);
if ($found_index === min(array_keys($keys)) && $increment === -1) {
$found_index = max(array_keys($keys))+1;
}
if ($found_index === max(array_keys($keys)) && $increment === +1) {
$found_index = min(array_keys($keys))-1;
}
return $keys[$found_index+$increment];
}
回答by Learner
If your data is large then it might be a best practice to avoid looping. You could make your own custom function, like so:
如果您的数据很大,那么避免循环可能是最佳做法。您可以创建自己的自定义函数,如下所示:
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
function previous($key, $array) {
$keysArray = array_keys($array);
$keyNumber = array_search($key, $keysArray);
if ($keyNumber === 0) {
$keyNumber = count($array);
}
return $array[$keysArray[$keyNumber - 1]];
}
var_dump(previous("second", $array));
Note that if you provide first key then it will return the last value, like a cyclic array. You can handle it however you like.
请注意,如果您提供第一个键,那么它将返回最后一个值,就像一个循环数组。你可以随心所欲地处理它。
With a bit tweak, you can also generalize it to return next values.
稍微调整一下,您还可以将其概括为返回下一个值。
As for why prev
isnt working is because it isnt used for that purpose. It just sets the internal pointer of the array to one behind, exact inverse of next
至于为什么prev
不起作用是因为它不用于该目的。它只是将数组的内部指针设置为一,正好相反next
I hope it helps
我希望它有帮助