选择元素时将数组视为圆形数组-PHP [英] Treat an array as circular array when selecting elements - PHP

查看:58
本文介绍了选择元素时将数组视为圆形数组-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环的数组。我有另一个数组,我需要从中一个个地选择一个数组,但是如果它到达数组的末尾,则需要绕行。为了清楚起见,这里是一些代码:

I have an array on which I loop over. I have another array from which I need to select one by one but it needs to go on circle in case it gets to the end of the array. To make it clear here is some code:

$mainArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$size      = count($mainArray);
$circular  = array('A', 'B', 'C');

for($i = 0; $i < $size; $i++) {
   echo $mainArray[$i] . ' = ' . $circular[$i] . ', ';
}

上面的代码将显示以下内容:

Now above code prints this:

1 = A, 2 = B, 3 = C, UNDEFINED INDEX ERROR

我需要打印的是:

1 = A, 2 = B, 3 = C, 4 = A, 5 = B, 6 = C, 7 = A, 8 = B, 9 = C, 10 = A

PHP是否有内置函数将数组转换为圆形数组?我想我需要使用模块化运算符来实现此目的。

Is there a built in function to PHP that turns an array into circular array? I think I need to use modular operator to achieve this.

推荐答案

获取圆形数组的大小( $ circsize ),然后针对它修改值 $ i 并将其用作索引:

Get the size of the circular array ($circsize)and then mod the value $i against it and use that as your index:

$mainArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$size      = count($mainArray);
$circular  = array('A', 'B', 'C');
$circsize  = count($circular);

for($i = 0; $i < $size; $i++) {
   echo $mainArray[$i] . ' = ' . $circular[$i % $circsize] . ', ';
}

这篇关于选择元素时将数组视为圆形数组-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆