从foreach循环创建逐块数组

时间:2019-03-21 04:50:39

标签: php arrays for-loop foreach

嗨,我正在尝试打印带有选定块e.x的多个数组。 2/3 但是我没有得到确切的结果。我需要帮助。
这是我的程序

  <?php
        $process_block = 2;// this is the block 
        $args = array(
        0=> 16083,
        1=> 16090);
        $user_id_start = $args[0];
        $user_id_end = $args[1];

        $end_page = ($user_id_end - $user_id_start)/$process_block ;

        if ($end_page > floor($end_page)){
            $end_page = floor($end_page)+1;
        }

        for($i=1; $i<=$end_page; $i++){
            if($i==$end_page){
                $id_from = ($user_id_start + ($i-1) * $process_block + 1);
                $id_to = $user_id_end;
            }elseif($i==1){
                $id_from = $user_id_start;
                $id_to = $user_id_start + $i * $process_block;
            }else{
                $id_from = ($user_id_start + ($i-1) * $process_block + 1);
                $id_to = $user_id_start + $i * $process_block;
            }
            $param['id_from'] = isset($id_from) ? $id_from : '';
             $param['id_to'] = isset($id_to) ? $id_to : '';
            print_r($param);
        }
        ?>

及其产生的输出:

 Array
    (
        [id_from] => 16083
        [id_to] => 16085
    )
    Array
    (
        [id_from] => 16086
        [id_to] => 16087
    )
    Array
    (
        [id_from] => 16088
        [id_to] => 16089
    )
    Array
    (
        [id_from] => 16090
        [id_to] => 16090
    )

我期望的数组应该像这样。数字之间有2个差异

  Array
(
    [id_from] => 16083
    [id_to] => 16085
)
Array
(
    [id_from] => 16086
    [id_to] => 16088
)
Array
(
    [id_from] => 16089
    [id_to] => 16090
)

Fiddle

1 个答案:

答案 0 :(得分:1)

我以为我会一口气把它搅成一团。但这可能是版本... 4?我觉得应该有一个更简单的解决方案,但是我确定没有找到它。它也应该处理范围大小的变化。

   <?php
            $process_block = 3;// this is the block 
            $args = array(
            0=> 16083,
            1=> 16090);
            $user_id_start = $args[0];
            $user_id_end = $args[1];

            $diff = $user_id_end - $user_id_start;
            $pages = ceil(($user_id_end - $user_id_start) / $process_block);

            for($i=0; $i<=$pages; $i++){
                if (($user_id_start+$i*$process_block)>$user_id_end)break;
                echo $i.'--'.($user_id_start+$i*$process_block).':::';
                $param['id_from'] = $i*$process_block+$user_id_start;
                $page_end = ($i+1) * $process_block+$user_id_start-1;
                $param['id_to'] = $page_end>$user_id_end ? $user_id_end : $page_end;
                print_r($param);
            }
            ?>