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条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了