使用密钥 php 获取下一个数组项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6407795/
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
Get the next array item using the key php
提问by Daric
I have an array
我有一个数组
Array(1=>'test',9=>'test2',16=>'test3'... and so on);
how do I get the next array item by passing the key.
如何通过传递密钥来获取下一个数组项。
for example if i have key 9
then I should get test3
as result. if i have 1
then it should return 'test2'
as result.
例如,如果我有钥匙,9
那么我应该得到test3
结果。如果我有1
那么它应该'test2'
作为结果返回。
Edited to make it More clear
编辑以使其更清晰
echo somefunction($array,9); //result should be 'test3'
function somefunction($array,$key)
{
return $array[$dont know what to use];
}
回答by deceze
function get_next($array, $key) {
$currentKey = key($array);
while ($currentKey !== null && $currentKey != $key) {
next($array);
$currentKey = key($array);
}
return next($array);
}
Or:
或者:
return current(array_slice($array, array_search($key, array_keys($array)) + 1, 1));
It is hard to return the correct result with the second method if the searched for key doesn't exist. Use with caution.
如果搜索到的键不存在,则使用第二种方法很难返回正确的结果。谨慎使用。
回答by Hardik Thaker
You can use next(); function, if you want to just get next coming element of array.
您可以使用 next(); 函数,如果您只想获取数组的下一个元素。
<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>
Update
更新
and if you want to check and use that next element exist you can try :
如果您想检查并使用下一个元素是否存在,您可以尝试:
Create a function :
创建一个函数:
function has_next($array) {
if (is_array($array)) {
if (next($array) === false) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Call it :
称它为 :
if (has_next($array)) {
echo next($array);
}
Source : php.net
来源:php.net
回答by Pham
$array = array("sony"=>"xperia", "apple"=>"iphone", 1 , 2, 3, 4, 5, 6 );
foreach($array as $key=>$val)
{
$curent = $val;
if (!isset ($next))
$next = current($array);
else
$next = next($array);
echo (" $curent | $next <br>");
}
回答by Rushil Pachchigar
<?php
$users_emails = array(
'Spence' => '[email protected]',
'Matt' => '[email protected]',
'Marc' => '[email protected]',
'Adam' => '[email protected]',
'Paul' => '[email protected]');
$current = 'Paul';
$keys = array_keys($users_emails);
$ordinal = (array_search($current,$keys)+1)%count($keys);
$next = $keys[$ordinal];
echo $next;
?>
回答by Bajrang
You can print like this :-
你可以这样打印:-
foreach(YourArr as $key => $val)
{ echo next(YourArr[$key]);
prev(YourArr); }