如何從數組中獲取下一個值的值。 我有一個數組這樣PHP數組的下一個值
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
如何獲得「四」或「九連」下一個值。
如何從數組中獲取下一個值的值。 我有一個數組這樣PHP數組的下一個值
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
如何獲得「四」或「九連」下一個值。
如果是這樣的話,你應該先準備好你的數組。根據你給定的數組,似乎這個索引不是連續正確的。嘗試使用array_values()函數。
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
$new_items = array_values($items);
$new_items = array(
[0] => 'two',
[1] => 'four',
[2] => 'three',
[3] => 'seven',
[4] => 'nine',
[5] =>'five'
);
然後,你可以做的foreach ..
foreach($new_items as $key => $value) {
// Do the code here using the $key
}
我this
$input = "nine";
$items = array(
'1' => 'two',
'9' => 'four',
'7' => 'three',
'6'=>'seven',
'11'=>'nine',
'2'=>'five'
);
$keys = array_keys($items);
$size = count($keys);
$foundKey = array_search($input,$items);
if($foundKey !== false)
{
$nextKey = array_search($foundKey,$keys)+1;
echo "your input is: ".$input."\n";
echo "it's key is: ".$foundKey."\n";
if($nextKey < $size)
{
echo "the next key => value is: ".$keys[$nextKey]." => ".$items[$keys[$nextKey]]."\n";
}
else
{
echo "there are no more keys after ".$foundKey;
}
}
的想法是,因爲鍵是不以任何真正爲了我需要做的通過獲取所有密鑰並將它們放入一個數組中,以便它們的整數鍵是我們的順序來輕鬆遍歷順序。這種方式'1'
= 0,'9'
= 1,'11'
= 4.
從那裏我然後找到哪個鍵匹配我們的輸入。如果我發現它,我得到該鍵和+ 1(下一個鍵)的位置。從那裏我可以使用$keys
中的字符串值在我們輸入+1的位置參考$items
中的數據。
如果我們的輸入是'five'
我們遇到問題,因爲'five'
是我們數組中的最後一個值。因此最後一條if語句會檢查下一個鍵的索引是否小於鍵的數目,因爲我們所擁有的最大索引是5,鍵的數量是6.
雖然可以使用array_values
使用有序的整數鍵將所有值存入數組中,通過這樣做,可以將原始密鑰丟失,除非您還使用了array_keys
。如果你使用array_keys
第一那麼就真的沒有必要使用array_values
希望這有助於:
while (($next = next($items)) !== NULL) {
if ($next == 'three') {
break;
}
}
$next = next($items);
echo $next;
的大陣u可以使用:
$src = array_search('five',$items); // get array key
$src2 = array_search($src,array_keys($items)); // get index array (start from 0)
$key = array_keys($items); // get array by number, not associative anymore
// then what u need just insert index array+1 on array by number ($key[$src2+1])
echo $items[$key[$src2+1]];
感謝您的回答它將解決我的問題。 –
lol。但我很高興它幫助某人,但我認爲你需要完成我的答案,如果搜索最後陣列或搜索不在陣列中。 –
這會遇到非常大的陣列,其中有...... 1000個值的問題。如果該值是第985個值,則在獲得答案之前,必須等待循環的985次迭代。 –
你可以做的foreach不首先使用array_values。這解決了什麼? –