Next key in array

2020-06-11 07:51发布

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.

标签: php arrays
7条回答
We Are One
2楼-- · 2020-06-11 08:27

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:

$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().

查看更多
不美不萌又怎样
3楼-- · 2020-06-11 08:35

use a combo of next and each to get both the key and value of the next item:

next($array)
$keyvalueArray = each ( $array )

$keyvalueArray should now hold the next key and value as 'key' and 'value'

http://www.php.net/manual/en/function.each.php

查看更多
甜甜的少女心
4楼-- · 2020-06-11 08:37

you can use a 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
查看更多
趁早两清
5楼-- · 2020-06-11 08:40
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.

查看更多
▲ chillily
6楼-- · 2020-06-11 08:42

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];
查看更多
唯我独甜
7楼-- · 2020-06-11 08:43
$next = next($array); 
echo key($array);

Should return the key corresponding to $next;

查看更多
登录 后发表回答