填充从上到下尽可能均匀分布的4个阵列


Populate 4 arrays evenly distributed as much as possible from top to bottom

这个问题与这篇文章有关如何在一个由4个数组组成的多维数组中分发mysql结果集

我得到了公认的答案,但现在我想对代码进行更改,但我没有太多成功。。。

基本上,从mysql结果集中,我需要从上到下填充尽可能均匀分布的4个数组。。。Chris Hayes提供了一个有效的解决方案,但当我今天测试它时,我意识到它从左到右填充数组,而不是从上到下。。。

如何更改代码,使其从上到下尽可能多地填充4个数组?

$i = 0;
$array_r = array( array(), array(), array(), array() );
while ($stmt->fetch()) {
    array_push($array_r[$i], array(... values ...));
    $i = ($i + 1) % 4;
}

完全不操作输入数组的最终版本:

for ($num = count($input), $offset = 0; $numBuckets > 0; $numBuckets -= 1, $num -= $bucketSize, $offset += $bucketSize) {
  $bucketSize = ceil($num / $numBuckets);
  $output[] = array_slice($input, $offset, $bucketSize);
}

上一个答案

尝试以下操作:

<?php
$input = range('A', 'Z'); // test input data
$output = array();        // the output container
$numBuckets = 4;          // number of buckets to fill
for (; $numBuckets > 0; $numBuckets -= 1) {
  $output[] = array_splice($input, 0, ceil(count($input) / $numBuckets));
}
print_r($output);

替代版本,没有常数重新检查阵列的长度

for ($num = count($input); $numBuckets > 0; $numBuckets -= 1, $num -= $bucketSize) {
  $bucketSize = ceil($num / $numBuckets);
  $output[] = array_splice($input, 0, $bucketSize);
}

这个片段应该适合您:

<?php
$array= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$strays = count($array)%4;
$offset = 0;
$results = array();
for($x = 0; $x < 4; $x++){
    if ($x < $strays){
        $size = (floor(count($array)/4) + 1);
    } else {
        $size = (floor(count($array)/4));
    }
    $results[] = array_slice($array, $offset, $size);
    $offset+=$size;
}
print_r($results);

我测试了一些东西,它似乎可以工作。。。但它看起来很像意大利面条。。。请随时优化代码。谢谢

$num_rows = $stmt->num_rows; //number of records returned by the result set
$min_per_column = (int)($num_rows/4); //minimum records per column
$remainder = $num_rows % 4; //the remainder
$array_r = array(array(), array(), array(), array());
$i = 1;
$col = 0;
//how many records to populate before moving to the next array?
$rows = ($col < $remainder) ? $min_per_column + 1 : $min_per_column;
while ($stmt->fetch()) {
    array_push($array_r[$col], array($r_recordingid, $r_title, $r_subtitle, $r_seourl));
    $i++;
    //initialize values for new array
    if ($i > $rows) {
       $i = 1;
       $col++;
       $rows = ($col < $remainder) ? $min_per_column + 1 : $min_per_column;
    }
}