dragon5006 2012-10-28 10:56
浏览 20
已采纳

PHP:有一种优雅的方式可以一次预测多个项目(组)吗?

Given an array of N items:

$arr = array('a', 'b', 'c', 'd', 'e', 'f');

What's the most elegant way to loop through in groups of M items (assuming N is divisible by M)?

I tried

foreach (array_chunk($arr, 2) as list($first, $second)) {
    // do stuff with $first and $second
}

but this resulted in a syntax error.

In other words, I want to emulate what in Tcl would look like this:

set arr [a b c d e f]
foreach {first second} $arr {
    // do stuff with $first and $second
}

For now I've resorted to the obvious measure:

foreach (array_chunk($arr, 2) as $group) {
    $first  = $group[0];
    $second = $group[1];
    // do stuff with $first and $second
}

But I'm hoping someone has a more elegant method...

  • 写回答

5条回答 默认 最新

  • dongwen4630 2012-10-28 11:06
    关注

    I'd alter your last variant to

    foreach (array_chunk($arr, 2) as $group) {
        list( $first, $second) = $group;
        // do stuff with $first and $second
    }
    

    Any other solution I thought about, would be more complex, like

    for ( $i = 0; $i < ceil(count($arr)/2) ; $i++) {
        $first = $arr[$i*2];
        $second = $arr[$i*2+1];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接