2012-08-01 24 views
0

我需要能够循环一个项目的数组,并给他们从另一个数组的值,我不能让我的头靠得很近。PHP - 序列通过数组并重复[modulo-operator]

我的数组

$myarray = array('a','b','c'); 

可以说我有过总共6项的foreach循环和我循环。

我如何得到以下输出

item1 = a 
item2 = b 
item3 = c 
item4 = a 
item5 = b 
item6 = c 

我的代码看起来是这样的。

$myarray = array('a','b','c'); 
$items = array(0,1,2,3,4,5,6); 
foreach ($items as $item) { 
    echo $myarray[$item]; 
} 

在线示例。 http://codepad.viper-7.com/V6P238

我想,当然能够循环通过无数次的量

+0

使用foreach循环嵌套在一个for循环,运行for循环,只要你希望它运行 – 2012-08-01 17:33:26

+0

使用'for'循环。另外,你有什么尝试? – rdlowrey 2012-08-01 17:33:30

+0

我尝试了一个for循环,我明显因为没有相应的键/值而陷入项目4,因为在$ myarray中没有相应的键/值。 – Blowsie 2012-08-01 17:37:15

回答

5
$myarray = array('a','b','c'); 
$count = count($myarray); 
foreach ($array as $index => $value) { 
    echo $value . ' = ' . $myarray[$index % $count] . "\n"; 
} 

%modulo-operator。它返回

剩余的$ a除以$ b。

拿什么

0 % 3 = 0 
1 % 3 = 1 
2 % 3 = 2 
3 % 3 = 0 
4 % 3 = 1 

等。在我们的例子中,这反映了我们想要检索的数组$myarray的索引。

+0

为什么'$ index%$ count'如果你只是做一个'foreach'呢?它仍然与'$ index'相同。 – Palladium 2012-08-01 17:42:58

+0

@钯不,它不是。 '$ index'是当前'$ value'的索引,而'$ count'是一个静态值。 – KingCrunch 2012-08-01 17:44:35

+0

是的。被定义为元素数字键的'$ index'永远不会高于'$ count'(给定他的测试数组)。您的'foreach'循环中不会出现'3%3'和'4%3'的情况。 – Palladium 2012-08-01 17:45:18

1

如果你想要做循环的任意号码,你可以通过你的密钥使用模运算循环:

$loop = //how much you want the loop to go 
//... 
for ($i = 0, $i < $loop, $i++) { 
    $key = $i % count($myarray); 
    echo $i, ' = ', $myarray[$key]; 
} 
1

我认为你要找的是modulo operator。尝试是这样的:

for ($i = 1; $i <= $NUMBER_OF_ITEMS; $i++) { 
    echo "item$i = ".$myarray[$i % count($myarray)]."\n"; 
}