让我有一个像这样的数组
Array
(
[126] => pitch
[134] => pithc2
[155] => pithc3
[87] => pithc4
[45] => pithc5
[192] => pithc6
)
现在有没有办法从特定键应用此数组中的循环?
示例:我想在155
之后输出,然后输出看起来像
1. pitch4,
2. pithc5
3. pithc6
如果我想在45
之后获得输出,那么输出看起来像
1. pithc6
答案 0 :(得分:2)
这应该适合你:
在这里,我使用reset()
,next()
,current()
,key()
,end()
按照您的意愿循环播放数组
<?php
$arr = array(126 => "pitch", 134 => "pithc2", 155 => "pithc3", 87 => "pithc4", 45 => "pithc5", 192 => "pithc6");
$from = 134;
//Get last element + rest the array
$end = end($arr);
reset($arr);
//set array pointer to '$from'
while(key($arr) != $from) next($arr);
while(current($arr) != $end) {
next($arr);
//prints the current array element and goes to the next one
echo current($arr) . "<br />";
}
?>
输出:
pithc3
pithc4
pithc5
pithc6
如果你想限制应该打印多少元素,你可以使用它:
<?php
$arr = array(126 => "pitch", 134 => "pithc2", 155 => "pithc3", 87 => "pithc4", 45 => "pithc5", 192 => "pithc6");
$from = 134;
$howmany = 6;
//Get last element + rest the array
$end = end($arr);
reset($arr);
//set array pointer to '$from'
while(key($arr) != $from) next($arr);
//go through '$howmany' times
for($i = 0; $i < $howmany; $i++) {
//prints the current array element and goes to the next one
echo current($arr) . "<br />";
//rest the array to the beginning, while it reached the end
if(current($arr) == $end)
reset($arr);
else
next($arr);
}
?>
输出:
pithc2
pithc3
pithc4
pithc5
pitch6
pithc