Marco
Marco

Reputation: 2737

How to distribute mysql result set in an multidimensional array of 4 arrays

I’m going crazy with this one... trying to figure it out for almost 4 hours with no success...

I'm trying to fetch a mysql query result set in a multidimensional array of 4 arrays. So if the result set returns 8 records, the array will contain 4 arrays of 2 records. If the result set returns 20 records, the array will contain 4 arrays of 5 records, and so on... That's the easy part...

The thing I’m having trouble with is when the result set cannot be distributed evenly in 4 arrays. For example, if the result set returns 14 records, then the first array contains 4 records, the second array contains 4 records , the third array 3 records and the fourth array 3 records...

Here’s what I’ve coded so far:

...

$num_rows = $stmt->num_rows; //number of records returned by the result set
$arrays = 4; //distributed in 4 arrays

$per_array = (int)($num_rows / $arrays); //minimum per array
$remainder = $num_rows % $per_array; //the remainder

$array_r = array();
$i = 1;
$col = 1;

while ($stmt->fetch()) {
    if ($i <= $per_array) {
        $i++;
    } else {
        $i = 1;
        $col++;
    }

    $array_r[$col][] = array(...values from result set...);
}

Upvotes: 0

Views: 230

Answers (2)

Chris Hayes
Chris Hayes

Reputation: 12020

Sounds like you're overthinking it.

$i = 0;
// Create 4 subarrays (you could do this programmatically as well)
$array_r = array( array(), array(), array(), array() );
while ($stmt->fetch()) {
    array_push($array_r[$i], array( ... values ... ));
    $i = ($i + 1) % 4;
}

Upvotes: 3

Majid Fouladpour
Majid Fouladpour

Reputation: 30252

Why not getting the result set into an array and then using array_chunk?

Upvotes: 1

Related Questions