2011-05-26 115 views
2

这看起来很容易,但我不能弄明白下一个元素

$users_emails = array(
'Spence' => '[email protected]', 
'Matt' => '[email protected]', 
'Marc' => '[email protected]', 
'Adam' => '[email protected]', 
'Paul' => '[email protected]'); 

我需要得到下一个元素的数组中,但我不能图出来......因此,例如

如果我有

$users_emails['Spence'] 

我需要返回[email protected],如果它的

$users_emails['Paul'] 

我需要从顶部开始并返回[email protected]

我想这

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

,这也

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

,但他们不回什么,我期待

+0

关联数组是否有序? – Hyperboreus 2011-05-26 16:20:00

+0

您在密钥中使用的名称是一次性输入,还是需要使用相应的电子邮件打印所有值? – tkm256 2011-05-26 16:20:11

+0

可能想为此创建一个循环链表。 – Wiseguy 2011-05-26 16:21:52

回答

0

你会更好地将这些存储在索引数组中以实现您正在寻找的功能

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

Reset()将数组指针倒回到第一个元素,each()以数组的形式返回当前的元素键和值,然后移动到下一个元素。

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 

要导航可以使用下一个($阵列),一个先前($阵列),复位($阵列),端部($阵列),而数据是使用电流($阵列)读取和/或关键($数组)。

或者,如果您遍历所有的人都可以使用的foreach

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

你可以做这样的事情:

$users_emails = array(
'Spence' => '[email protected]', 
'Matt' => '[email protected]', 
'Marc' => '[email protected]', 
'Adam' => '[email protected]', 
'Paul' => '[email protected]'); 

$current = 'Spence'; 
$keys = array_keys($users_emails); 
$ordinal = (array_search($current,$keys)+1)%count($keys); 
$next = $keys[$ordinal]; 
print_r($users_emails[$next]); 

不过我想你可能在你的逻辑和你有一个错误你正在做的事情可以做得更好,比如使用foreach循环。