next()
和prev()
是否适用于关联数组?
我正试图遍历一个使用两条记录来描述一个“游戏”的数据集,如果你愿意的话。因此,当我在第二个记录上匹配id时,我需要先查看记录并抓住eg_item['final_score']
。
{"id":"75", "team_name":"TEAM1", "home_team_name":"TEAM1", "image":"TEAM1_HOME.png", "final_score":"37"},
{"id":"75", "team_name":"TEAM2", "home_team_name":"TEAM2", "image":"TEAM2_AWAY.png", "final_score":"10"},
{"id":"76", "team_name":"TEAM1", "home_team_name":"TEAM1", "image":"TEAM1_HOME.png", "final_score":"10"},
{"id":"76", "team_name":"TEAM2", "home_team_name":"TEAM2", "image":"TEAM2_AWAY.png", "final_score":"14"},
我发现的所有示例都使用了蹩脚的array('one','two',three')
类型示例,这些示例无济于事。
代码示例:
foreach( $json_output as $eg_item ) :
if( $this_game_id == $last_game_id ) :
// get this records info
$b_score = $eg_item['final_score'];
$b_team_name = $eg_item['team_name'];
prev( $json_output );
// get previous records info
$a_score = $eg_item['final_score'];
$a_team_name = $eg_item['team_name'];
$a_game_id = $eg_item['id'];
// put pointer back
next( $json_output );
else :
// skip next record
endif;
endforeach;
答案 0 :(得分:0)
看起来像是一组关联数组,对吗?如果是这样,一次通过索引2遍历它们,那么你可以在循环的每次迭代中查看当前内部数组和前一个内部数组:
for ($i = 1; $i < count($array); $i+= 2) {
$current = $array[$i];
$last = $array[$i-1];
//$current['final_score'], $last['final_score'], etc
}
答案 1 :(得分:0)
是的,他们工作得很好,这是我做过的一个小测试案例:
<?php
$sample = array(
"first" => Array("a","d","c"),
"second" => Array("a","d","c"),
"third" => Array("a","d","c"),
"fourth" => Array("a","d","c")
);
while(next($sample))
{
$item = current($sample);
echo key($sample) . "\n";
if(is_array($item))
{
echo "\t" . current($item) . "\n";
while(next($item))
{
echo "\t" . current($item) . "\n";
}
}
}
?>