关联php数组中的下一个元素 [英] next element in a associative php array

查看:272
本文介绍了关联php数组中的下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很简单,但我无法弄清楚

This seems so easy but i cant figure it out

$users_emails = array(
'Spence' => 'spence@someplace.com', 
'Matt'   => 'matt@someplace.com', 
'Marc'   => 'marc@someplace.com', 
'Adam'   => 'adam@someplace.com', 
'Paul'   => 'paul@someplace.com');

我需要获取数组中的下一个元素,但是我无法弄清楚……所以例如

I need to get the next element in the array but i cant figure it out... so for example

如果我有

$users_emails['Spence']

我需要返回matt@someplace.com,如果返回

I need to return matt@someplace.com and if Its

$users_emails['Paul'] 

我需要从头开始,然后返回spence@someplace.com

i need start from the top and return spence@someplace.com

我尝试过

$next_user = (next($users_emails["Spence"]));

这也是

 ($users_emails["Spence"] + 1 ) % count( $users_emails )

但是他们没有返回我所期望的

but they dont return what i am expecting

推荐答案

reset($array);
while (list($key, $value) = each($array)) { ...

Reset()将数组指针回退到第一个元素,each()返回当前元素的键和值作为数组,然后移至下一个元素.

Reset() rewind the array pointer to the first element, each() returns the current element key and value as an array then move to the next element.

list($key, $value) = each($array);
// is the same thing as
$key = key($array); // get the current key
$value = current($array); // get the current value
next($array); // move the internal pointer to the next element

要导航,可以使用next($array)prev($array)reset($array)end($array),同时使用current($array)和/或key($array)读取数据.

To navigate you can use next($array), prev($array), reset($array), end($array), while the data is read using current($array) and/or key($array).

或者,如果您遍历所有这些,则可以使用foreach

Or you can use foreach if you loop over all of them

foreach ($array as $key => $value) { ...

这篇关于关联php数组中的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆