phparraysgrouping

Split a flat array into a 2d array with N elements in each row (padded with null elements to ensure full rows)


I have the data in the array form as:

0 => a,
1 => b,
2 => c,
3 => d,
4 => e,
5 => f,
6 => g

How can I convert these array into the following one?

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

Solution

  • Live DEMO

    Consider this code:

    $j = 0;
    for($i=0; $i< count($arr); $i++){
        if(($i !=0) && (($i % 2) == 0)){
            $j++;
        }
        $newArray[$j][] = $arr[$i];
    }
    
    $lastElement = count($newArray) -1;
    if(count($newArray[$lastElement]) < 2){
        $newArray[$lastElement][]= null;
    }
        
    echo "<pre>";
    print_r($newArray); 
    

    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] => 
            )
    
    )