drby30217 2015-06-30 14:57
浏览 72
已采纳

选择元素时,将数组视为圆形数组 - 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

What I need it to print is this:

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

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.

  • 写回答

4条回答 默认 最新

  • dongtao9095 2015-06-30 15:00
    关注

    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] . ', ';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制