duanmei1930 2013-09-24 23:56
浏览 35
已采纳

逐步使用PHP数组循环并检查它是否已达到最大值

I have 200 boxes of which to be named from an array. All names go sequentially and will restart from the first value in the array once previous Box has taken the last name (maximum value?) from the array.

$BoxName = array (Name1, Name2, Name3, Name4, Name5);

The name of first box is always determined by Users through their inputs. The rest of other boxes through coding.

Now i'm using very untrained approach: If Box1 = Name3, given by User's input:

Box1 = Name3 //given by the user

$BoxName = array (Name1, Name2, Name3, Name4, Name5);

$a = 3; //This is given by the User
$b = $a + 1;

if ( $b <= 5 ) {
    $c = $a + 1;
} else {
    $c = 1;
}

$d = $c + 1;

if ( $d <= 5 ) {
    $e = $c + 1;
} else {
  $e = 1;
}
echo $Box1 = $BoxName [3]; // this is given by the user
echo $Box2 = $BoxName [$c];
echo $Box3 = $BoxName [$e];
// ... ... and the list goes on for another 197 boxes.

?>

It obviously looks messy, incorrect and dirty. As a non IT trained dummy, this is the best i can achieve.

  • 写回答

2条回答 默认 最新

  • dongzhan1948 2013-09-25 00:09
    关注

    Here is where the modulus operator (%) is your friend.

    $max_boxes = 200;
    $start_box = 3; // box to start with from your example - this is 1-based offset value sent from user
    $start_box_offset = $start_box - 1; // box_start position within zero-based array
    
    $box_names = array ('Name1', 'Name2', 'Name3', 'Name4', 'Name5');
    $box_name_count = count($box_names);
    $box_output = array();
    
    for ($i = 0; $i < $max_boxes; $i++) {
        $modulus = ($i + $start_box_offset) % $box_name_count;   
        $box_output[] = $box_names[$modulus];
    }
    

    Note that I have output as array instead of $box1, $box2, etc. as it would be much easier to work with.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线