我试图在foreach循环中获取$ current_account,直到fooreach循环结束。我正在使用下一个函数,它给出了数组中的下一个元素,直到它到达结尾。如何在数组到达数组末尾时将其转到数组中的第一个元素?
$search_tags = array(
"happy",
"summer",
"beach",
"glasses",
"umbrella",
"funny",
"people",
"music",
"rap"
);
$accounts = array(
"account A",
"account B",
"account C"
);
foreach ($search_tags as $tag) {
$current_account = current($accounts);
print_r($current_account."\n");
};
所以在这种情况下结果应该是这样的:
帐户B. 帐户C. 帐户A. 帐户B. 帐户C. 帐户A. 帐户B. 帐户C. 帐户A
但我得到以下内容:
帐户B. 帐户C
答案 0 :(得分:4)
使用InfiniteIterator
$accounts = new InfiniteIterator(new ArrayIterator($accounts));
$accounts->rewind();
foreach($search_tags as $tag) {
echo ucfirst($accounts->current()), PHP_EOL;
$accounts->next();
}
答案 1 :(得分:0)
还有其他简单的方法,例如通过索引访问帐户元素,具体取决于当前索引,如下所示;
foreach ($search_tags as $index => $tags) {
print_r($accounts[$index % count($accounts)] . "\n");
}
哪些输出;
account A
account B
account C
account A
account B
account C
account A
account B
account C