0

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...);
}
Marco
  • 2,687
  • 7
  • 45
  • 61

2 Answers2

3

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;
}
Chris Hayes
  • 11,471
  • 4
  • 32
  • 47
1

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

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
  • I think he wants them evenly distributed as much as possible. That is, the arrays should be of size (4, 4, 3, 3) in his example, and not (4, 4, 4, 2). Whether that's a real requirement or not is up in the air. – Chris Hayes Aug 05 '13 at 05:46
  • @ChrisHayes That's exactly what i want... sorry, my english is not my first language – Marco Aug 05 '13 at 05:47
  • @ChrisHayes, the post leaves it vague whether `contains` is meant as a complaint or the objective. – Majid Fouladpour Aug 05 '13 at 05:50