0

The array has to be organized so that, rather than having each value in the array, the array values of arrays with the values of the data, and each of those nested arrays must have a max number of values.

So it should start with this:

$data = array(
  0 => 'Data 1',
  1 => 'Data 2',
  2 => 'Data 3',
  3 => 'Data 4',
  4 => 'Data 5',
  5 => 'Data 6',
);

and then given that $max = 3;, the array should become this:

$data = array(
  0 => array(
    0 => 'Data 1',
    1 => 'Data 2',
    2 => 'Data 3',
  ),
  1 => array(
    0 => 'Data 4',
    1 => 'Data 5',
    2 => 'Data 6',
  ),
);

I feel like I'm close, but I keep losing the fourth data value when my max is set to 3.

$max_col = 3;
$current_row = 0;
$current_col = 0;
foreach ($data_values as $val) {
  if ($current_col < $max_col) {
    $new_data[$current_row][$current_col] = $val;
    $current_col++;
  } else {
    $current_col = 0;
    $current_row++;
    $new_data[$current_row][$current_col] = $val;
  }
}

What I end up with is this:

$data = array(
  0 => array(
    0 => 'Data 1',
    1 => 'Data 2',
    2 => 'Data 3',
  ),
  1 => array(
    0 => 'Data 5',
    1 => 'Data 6',
  ),
);
2
  • 1
    Look at array_chunk() Commented Apr 14, 2015 at 19:56
  • Don't reinvent the wheel, use Jonathan's answer. It makes the intention of the code clear and because it's a native function, it runs much faster than user code. Commented Apr 14, 2015 at 20:40

3 Answers 3

2

Have a look at array_chunk

<?php
$data = array(
  0 => 'Data 1',
  1 => 'Data 2',
  2 => 'Data 3',
  3 => 'Data 4',
  4 => 'Data 5',
  5 => 'Data 6',
);

$newData = array_chunk($data, 3);

print_r($newData);

Outputs:

Array
(
    [0] => Array
        (
            [0] => Data 1
            [1] => Data 2
            [2] => Data 3
        )

    [1] => Array
        (
            [0] => Data 4
            [1] => Data 5
            [2] => Data 6
        )

)

http://codepad.viper-7.com/AwGZ5V

Sign up to request clarification or add additional context in comments.

Comments

1

Just increment $current_row at the end:

else {
    $current_col = 0;
    $new_data[$current_row][$current_col] = $val;
    $current_row++;
  }

Comments

1

your code is almost ok except a minor addition

 $max_col = 3;
 $current_row = 0;
 $current_col = 0;
 foreach ($data_values as $val) {
  if ($current_col < $max_col) {
    $new_data[$current_row][$current_col] = $val;
    $current_col++;
    } else {
      $current_col = 0;
      $current_row++;
      $new_data[$current_row][$current_col] = $val;
      $current_col++; //this is the new line you have to add
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.