Split an Array into N Arrays - PHP

前端 未结 11 1769
一向
一向 2020-12-05 07:05

I have an array of 18 values:

$array = array(\'a\', \'b\', \'c\', \'d\', \'e\', \'f\', \'g\', \'h\', \'i\', \'j\', \'k\', \'l\', \'m\', \'n\', \'o\', \'p\',          


        
相关标签:
11条回答
  • 2020-12-05 07:47

    This simple function would work for you:

    Usage

    $array = range("a", "r"); // same as your array
    print_r(alternate_chunck($array,12));
    

    Output

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )
    
        [1] => Array
            (
                [0] => c
                [1] => d
            )
    
        [2] => Array
            (
                [0] => e
                [1] => f
            )
    
        [3] => Array
            (
                [0] => g
                [1] => h
            )
    
        [4] => Array
            (
                [0] => i
                [1] => j
            )
    
        [5] => Array
            (
                [0] => k
                [1] => l
            )
    
        [6] => Array
            (
                [0] => m
            )
    
        [7] => Array
            (
                [0] => n
            )
    
        [8] => Array
            (
                [0] => o
            )
    
        [9] => Array
            (
                [0] => p
            )
    
        [10] => Array
            (
                [0] => q
            )
    
        [11] => Array
            (
                [0] => r
            )
    
    )
    

    Update The above might not be useful for most cases ... here is another type of chunk

    $array = range("a", "r"); // same as your array
    print_r(fill_chunck($array, 5));
    

    Output

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
                [2] => c
                [3] => d
            )
    
        [1] => Array
            (
                [0] => e
                [1] => f
                [2] => g
                [3] => h
            )
    
        [2] => Array
            (
                [0] => i
                [1] => j
                [2] => k
                [3] => l
            )
    
        [3] => Array
            (
                [0] => m
                [1] => n
                [2] => o
                [3] => p
            )
    
        [4] => Array
            (
                [0] => q
                [1] => r
            )
    
    )
    

    This would make sure the group at no time is more that 5 elements where the other one has no limitation

    Function Used

    function alternate_chunck($array, $parts) {
        $t = 0;
        $result = array();
        $max = ceil(count($array) / $parts);
        foreach(array_chunk($array, $max) as $v) {
            if ($t < $parts) {
                $result[] = $v;
            } else {
                foreach($v as $d) {
                    $result[] = array($d);
                }
            }
            $t += count($v);
        }
        return $result;
    }
    
    
    function fill_chunck($array, $parts) {
        $t = 0;
        $result = array_fill(0, $parts - 1, array());
        $max = ceil(count($array) / $parts);
        foreach($array as $v) {
            count($result[$t]) >= $max and $t ++;
            $result[$t][] = $v;
        }
        return $result;
    }
    
    0 讨论(0)
  • 2020-12-05 07:51
    <?php
    function slotify($array, $length)
    {
        // Create a placeholder array and calculate the number of items
        // needed per slot (think card dealing LtoR).
        for(
            $slots = array_fill(0, $length, 0), $count=count($array), $i=0;
            $i<$count;
            $slots[$i % $length]++, $i++
        );
    
        // Now just take slices of the original array
        // depending on the calculated slot number and place in our slots
        foreach($slots as $k => $n) {
            $slots[$k] = array_splice($array, 0, $n);
        }
    
        return $slots;
    }
    
    var_export(slotify(['a','b','c','d','e','f'], 4));
    

    Output:

    array (
      0 => 
      array (
        0 => 'a',
        1 => 'b',
      ),
      1 => 
      array (
        0 => 'c',
        1 => 'd',
      ),
      2 => 
      array (
        0 => 'e',
      ),
      3 => 
      array (
        0 => 'f',
      ),
    )
    

    The intermediate array $slots holding number of items required would look like this for the example above:

    array (
      0 => 2,
      1 => 2,
      2 => 1,
      3 => 1,
    )
    

    If you study the different combinations for the intermediate array. You need to work out the boundary point where the chunk size changes. My solution gravitated towards the following, which is pretty much mickmacusa's final solution. But this requires understanding the problem.

    function slotify($array, $length)
    {
        $count      = count($array);
        $chunk_size = ceil($count/$length);
        $boundary   = $count % $length;
    
        if($boundary === 0)
            $boundary = $length;
    
        for($i=0; $i<$length; $i++) {
            if($i === $boundary)
                $chunk_size--;
            $result[$i] = array_splice($array, 0, $chunk_size);
        }
    
        return $result;
    }
    

    Further refinements can be made, slicing is probably more efficient than splicing, and if you can evenly distribute throughout the array, you could shortcut.

    0 讨论(0)
  • 2020-12-05 07:58

    You can use array_chunk and array_merge for this problem:

    <?php 
    
    $array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
    $chunked_arr = array_chunk($array,12);
    $j = 0;
    for($i = 0; $i < count($chunked_arr[0]); $i++){
        if(!($i % 2 == 0)){
            $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
            $j++;
        } else {
        $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
        }
    }
    
    $merged_array = array_merge($first_combined, $chunked_arr[1]); 
    
    echo '<pre>';
    print_r($merged_array);
     ?>
    

    And You will get the result like this:

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )
    
        [1] => Array
            (
                [0] => c
                [1] => d
            )
    
        [2] => Array
            (
                [0] => e
                [1] => f
            )
    
        [3] => Array
            (
                [0] => g
                [1] => h
            )
    
        [4] => Array
            (
                [0] => i
                [1] => j
            )
    
        [5] => Array
            (
                [0] => k
                [1] => l
            )
    
        [6] => m
        [7] => n
        [8] => o
        [9] => p
        [10] => q
        [11] => r
    )
    

    This is what exactly you want.

    Live Demo Here>>

    0 讨论(0)
  • 2020-12-05 07:59

    What you are describing is not what array_chunk is made for. You should use array_slice() and calculate yourself which parts of the array you want to end up as new arrays. (and use a for loop to iterate over your original array)

    Update:

    Some calculations that could help you:

    minimum_fill = floor(array_length / nr_buckets)
    bigger_buckets_amount = array_length - (minimum_fill / nr_buckets)
    

    Algorithm to fill buckets: Loop over the array, fill the first bigger_buckets_amount amount of buckets with (minimum_fill + 1), fill the rest of the buckets with minimum_fill

    0 讨论(0)
  • 2020-12-05 07:59

    Compile that and see if it does for you:

    <?php
    
    $array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');
    
    $sliceA = 0;
    $sliceB = 2;
    
    $final = array(array_slice($array, $sliceA, $sliceB));
    
    
    for ($i=$sliceB; $i<sizeof($array); $i++)
    {
        $final[$sliceB-1] = array($array[$i]);
        $sliceB++;
    }
    
    var_dump($final);
    
    0 讨论(0)
  • 2020-12-05 07:59

    This will do it for you!
    Here, I used my function smallify() to break an array of 15 elements into 3 arrays of 5 elements each.

    <?php
    
    $bigArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
    
    echo ("<pre>");
    print_r (smallify($bigArray, 3));
    echo ("<pre/>");
    
    
    function smallify($arr, $numberOfSlices){
    
      $sliceLength = sizeof($arr) /$numberOfSlices;
      for($i=1; $i<=$numberOfSlices; $i++){
    
           $arr1 = array_chunk($arr, $sliceLength*$i);
           return $arr1;
           unset($arr1);
    
       }
    
    }
    ?>
    

    Result

    Array
    (
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )
    
    [1] => Array
        (
            [0] => 6
            [1] => 7
            [2] => 8
            [3] => 9
            [4] => 10
        )
    
    [2] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 13
            [3] => 14
            [4] => 15
        )
    
    )
    
    0 讨论(0)
提交回复
热议问题