0

我试图在 foreach 循环中获取 $current_account ,直到 fooreach 循环结束。我正在使用 next 函数,它为我提供数组中的下一个元素,直到它到达末尾。到达数组末尾后,如何使其转到数组中的第一个元素?

$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

4

2 回答 2

4

利用InfiniteIterator

$accounts = new InfiniteIterator(new ArrayIterator($accounts));
$accounts->rewind();

foreach($search_tags as $tag) {
    echo ucfirst($accounts->current()), PHP_EOL;
    $accounts->next();
}

观看现场演示

于 2013-06-03T11:18:12.250 回答
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
于 2013-06-03T11:26:52.280 回答