2013-08-05 53 views
1

这个问题是关于这个帖子 How to distribute mysql result set in an multidimensional array of 4 arrays填充4阵列分布均匀,尽可能从上到下

我被接受的答案,但现在我想做出改变的代码,我没有很多的成功...

基本上,从一个MySQL的结果集,我需要填充4个数组尽可能从上到下均匀分布... 克里斯海耶斯提供了一个solutuon的工作,但当我今天测试它时,我意识到它将数组从左到右,而不是从上到下......

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

$i = 0; 
$array_r = array(array(), array(), array(), array()); 

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

如何的长度不*从左到右*和*从上到下*涉及数组? – Yoshi

+0

看看[array_chunk](http://www.php.net/array-chunk) – Orangepill

+0

@Yoshi:代码从左到右填充数组...换句话说,第二个值将在第二个数组中不是第一个数组的第二个值 – Marco

回答

3

最终版本,而在所有的操作输入数组:

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); 
} 
+0

测试和完美的作品......我甚至把一个计时器来测试速度和它的快速... – Marco

+0

@Marco欢迎您!;) – Yoshi

+1

@Marco正如你提到的速度,我添加了一个替代版本,它删除输入数组上的恒定长度检查。 – Yoshi

1

该段应为你工作:

<?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); 
+0

array_chunk在这种情况下不起作用coz 4个数组需要尽可能从上到下均匀分布...如果我有18行的结果集,array_chunk用5行填充第一个数组,第二个数组与5行,第5个数组的第3个数组和第3个数组的第3个数组......它需要是5,5,4,4 – Marco

+0

@Marco我明白你现在在做什么。 – Orangepill

+0

任何想法如何让这个工作?谢谢 – Marco

0

我测试过的东西,它似乎工作...但它看起来很面条......请随时优化代码。谢谢。

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