PHP重新组织一个数组

时间:2015-04-14 19:51:58

标签: php arrays loops foreach

必须对数组进行组织,以便不是在数组中包含每个值,而是使用数据值的数组的数组值,并且每个嵌套数组必须具有最大值。

所以它应该从这开始:

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

然后给出$max = 3;,数组应该变为:

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

我觉得我已经接近了,但是当我的最大值设置为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;
  }
}

我最终得到的是:

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

3 个答案:

答案 0 :(得分:2)

查看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);

输出:

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

答案 1 :(得分:1)

最后只需增加$ current_row:

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

答案 2 :(得分:1)

你的代码几乎没有问题,只有一点点添加

 $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
    }

}