php 数组中的下一个键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7454904/
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
Next key in array
提问by Jordy
I have an array:
我有一个数组:
$array=array(
"sdf"=>500,
"gsda"=>1000,
"bsdf"=>1500,
"bads"=>2000,
"iurt"=>2500,
"poli"=>3000
);
How can I get the name of the next key? For example if the current array is gsda
, I need bsdf
.
如何获取下一个键的名称?例如,如果当前数组是gsda
,我需要bsdf
.
采纳答案by Lars
If the pointer of current()
is on the right key, @Thomas_Cantonnet is right and you want to use next()
. If you did not iterate through the array via next(), you first have to go through the array to set the internal index pointer correctly:
如果 的指针current()
在正确的键上,@Thomas_Cantonnet 是正确的,您想使用next()
. 如果您没有通过 next() 遍历数组,则首先必须遍历数组以正确设置内部索引指针:
$search = "bsdf";
while (($next = next($array)) !== NULL) {
if ($next == $search) {
break;
}
}
Now $next points to your current search-index and you can iterate over the rest via next()
.
现在 $next 指向您当前的搜索索引,您可以通过next()
.
回答by RiaD
If pointer is not on this element, as other solutions assume, You can use
如果指针不在此元素上,正如其他解决方案所假设的那样,您可以使用
<?php
$keys = array_keys($arr);
print $keys[array_search("gsda",$keys)+1];
回答by Tom
$next = next($array);
echo key($array);
Should return the key corresponding to $next;
应该返回对应于 $next 的键;
回答by J_S
use a combo of next and each to get both the key and value of the next item:
使用 next 和 each 的组合来获取下一项的键和值:
next($array)
$keyvalueArray = each ( $array )
$keyvalueArray should now hold the next key and value as 'key' and 'value'
$keyvalueArray 现在应该将下一个键和值保存为“键”和“值”
回答by dev-null-dweller
next($array);
$key = key($array);
prev($array);
回答by shakram02
you can use a foreach
你可以使用 foreach
$test=array(
1=> array("a","a","a"),
2=> array("b","b","b"),
'a'=> array("c","c","c")
);
foreach (array_keys($test) as $value)
{
foreach ($test[$value] as $subValue)
{
echo $subValue." - ".$value;
echo "\n";
}
echo "\n";
}
output
输出
a - 1
a - 1
a - 1
b - 2
b - 2
b - 2
c - a
c - a
c - a
回答by The EasyLearn Academy
function get_next_key_array($array,$key){
$keys = array_keys($array);
$position = array_search($key, $keys);
if (isset($keys[$position + 1])) {
$nextKey = $keys[$position + 1];
}
return $nextKey;
// in above function first argument is array in which key needs to be searched and 2nd argument is $key which is used to get next key so it means you must one existing key of associative array from you which you want to get next keys.
// 在上面的函数中,第一个参数是需要搜索键的数组,第二个参数是 $key 用于获取下一个键,因此这意味着您必须从关联数组的一个现有键中获取下一个键。