[英]PHP get previous array element knowing current array key
我有一個帶有特定鍵的數組:
array(
420 => array(...),
430 => array(...),
555 => array(...)
)
在我的應用程序中,我知道當前密鑰(例如555
)。 我想得到前一個數組元素。 在此示例中,它是鍵為430
的數組元素。 如何在 PHP 中執行此操作? 我嘗試使用prev()
,但是對於這個 function 我們應該知道當前的數組元素。 沒找到function,什么設置了當前數組元素。
一種選擇:
要將內部指針設置為某個位置 ,您必須轉發它(使用key
和next
,可能之前執行reset
以確保從數組的開頭開始):
while(key($array) !== $key) next($array);
然后你可以使用prev()
:
$prev_val = prev($array);
// and to get the key
$prev_key = key($array);
根據之后要對陣列執行的操作,您可能需要reset
內部指針。
如果數組中不存在該鍵,則會出現無限循環,但這可以通過以下方式解決:
while(key($array) !== null && key($array) !== $key)
當然prev
不會再給你正確的價值,但我認為你要搜索的密鑰無論如何都會在數組中。
快速查找解決方案:(如果必須多次執行此操作)
$keys = array_flip(array_keys($array));
$values = array_values($array);
return $values[$keys[555]-1];
array_flip
(
array_keys
($array));
將返回一個數組映射鍵到它們在原始數組中的位置,例如array(420 => 0, 430 => 1, 555 => 2)
。
並且array_values
()返回一個數組映射位置到值,例如array(0 => /* value of $array[420] */, ...)
。
所以$values[$keys[555]-1]
有效地返回前面的元素,假設當前元素有鍵555。
替代方案:
$keys = array_keys($array);
return $array[$keys[array_search(555, $keys)-1]];
我用這種方式解決了這個問題:
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前一個鍵,如果沒有以前的鍵,則返回false
例:
$myhash = array(
'foo' => 'foovalue',
'goo' => 'goovalue',
'moo' => 'moovalue',
'zoo' => 'zoovalue'
);
echo "TEST: ". getPrevKey('zoo', $myhash); // prints moo
@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;
}
用法:
// previous key
getAdjascentKey( $key, $hash, -1 );
// next key
getAdjascentKey( $key, $hash, +1 );
例子:
$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
您可以反向遍歷數組,並在找到搜索值后返回下一個迭代。
$found = false;
foreach(array_reverse($array, true) as $key=>$value) {
if ($found) {
print "$key => $value\n";
break;
} else if ($key == 555) {
$found = true;
}
}
只是迭代數組
$_index = null;
foreach($myarray as $index => $value)
{
if($key == $my_index) // if($key == 550)
{
break;
}
$_index = $index;
}
echo $_index; //the prev key from 550;
另一種解決方案是將數組的鍵放在枚舉數組中,如下所示:
$keys = array_keys($my_array);
由於keys數組是索引,你可以移動上一個鍵,如下所示:
$required_key = (array_search(550,$keys,true) - 1);
這將罰款550
的值,並在鍵內返回其索引,刪除一個以獲取以前的索引
key我們有以前的鍵來從原始數組中獲取值
$value = $my_array[$required_key];
進一步擴展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];
}
如果您的數據很大,那么避免循環可能是最佳做法。 您可以創建自己的自定義函數,如下所示:
$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));
請注意,如果提供第一個鍵,則它將返回最后一個值,如循環數組。 你可以隨意處理它。
通過一些調整,您還可以將其概括為返回下一個值。
至於為什么prev
工作是因為它不用於那個目的。 它只是將數組的內部指針設置為后面的一個,與next
完全相反
我希望它有所幫助
試試這個功能。 它在數組中找到給定值的當前鍵,然后從找到的鍵的位置,您可以使用 $increment 獲得下一個/上一個鍵,例如:當$increment=1
,它在$increment=2
時找到下一個鍵,下一個找到 2 key 當$increment=-1
,它會找到 1 個前一個鍵,依此類推。
function sov_find_key($findvalue, $array, $increment) {
reset($array);
$key = array_search($findvalue, $array);
if ($key === false || $key === 0){
return false;
}
if ($increment === 0){
return $key;
}
$isNegative = $increment < 0 ? true:false;
$increment = abs($increment);
while(key($array) !== $key) {
next($array);
}
$x=0;
while($x < $increment) {
if( $isNegative ){
prev($array);
} else {
next($array);
}
$x++;
}
return key($array);
}
演示: https : //3v4l.org/CSSmR
這是一個接受任何類型密鑰的單線解決方案,您可以在 function 中實現或按原樣使用:
$previousKey =
array_keys($yourArray)[
array_search(
$currentKey,
array_keys($yourArray)
) - 1
]
??
null;
例如:
$yourArray = [
30 => ['value1', 'value2', 'value3'],
'keyA' => ['valueA', 'valueB', 'valueC'],
8848 => ['valueX', 'valueY', 'valueZ']
];
echo
array_keys($yourArray)[
array_search(
'keyA',
array_keys($yourArray)
) - 1
]
??
null;
會回聲30
這是 function 的形式:
/**
* Given an array and a key, returns the key that precedes it.
* Works with hash arrays with any type of keys.
* @param array $array The array to search the previous key in
* @param mixed $pointerKey The key in the array that follows the key to be returned
* @return mixed The key that precedes the specified $pointerKey in the $array, or null if the $pointerKey was not found or was the first key.
*/
function getPreviousKey(
array $array,
mixed $pointerKey
): mixed {
return
array_keys($array)[
array_search(
$pointerKey,
array_keys($array)
) - 1
]
??
null;
}
請注意:
null
。??
,此代碼需要 PHP 版本 >= 7。這是一個簡單的解決方案,用於獲取前一個和下一個項目,即使我們位於數組的末尾。
<?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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.