2010-11-18 133 views
4
$a = array(8, 16, 16, 32, 8, 8, 4, 4); 

对于上面这样的数组,有一种方法可以根据设置的值对数组进行划分/拆分。例如,如果我希望它们等于32.我的最后一个数组将有多达100个值,全部为32,16,8或4,我只需要对这些项目进行分组,因此该值始终等于设定值,因此在本例中为32。按数值划分/按值拆分

从上述阵列我会希望得到:

$a[0][1] = 16 
$a[0][2] = 16 

$a[1][3] = 32 

$a[2][0] = 8 
$a[2][4] = 8 
$a[2][5] = 8 
$a[2][6] = 4 
$a[2][7] = 4 

为$ a [0]总结了32个也是如此$ A [1]和$一个[2]。

+2

为什么你会得到'[16,16],[32],[8,8,8,4 ,[4]]'而不是,例如'[[32],[8,8,16],[4,4,8,16]]'?或者没有关系? – 2010-11-18 16:24:30

+0

只要它们的总和为32就可以了。 – azzy81 2010-11-18 16:27:29

+0

借调 - 它们如何合并,只要它总计32?如果总数不是32的倍数,该怎么办? – Spudley 2010-11-18 16:30:07

回答

4
$a = array(8, 16, 16, 32, 8, 8, 4, 4); 
$limit = 32; 
rsort($a); 
$b = array(array()); 
$index = 0; 
foreach($a as $i){ 
    if($i+array_sum($b[$index]) > $limit){ 
     $b[++$index] = array(); 
    } 
    $b[$index][] = $i; 
} 
$a = $b; 
print_r($a); 

它会工作,但只是因为在你的情况下,你有4 | 8 | 16 | 32,并且只有当所需的总和是最大数量(32)的倍数时才是。

测试:http://codepad.org/5j5nl3dT

注:|意味着divides

+0

'|'是一个按位运算符,意思是“或”,你为什么不做'4/8/16/32'? – RobertPitt 2010-11-18 16:41:37

+0

@Robert我指的是数学中使用的'|'。对不起,如果它造成混乱。通过使用这个链接,我试图指出每个数字会将下一个数字分开。 '4/8/16/32'就等于'O',它没有告诉你什么。 – 2010-11-18 16:45:03

+0

没有问题,许多成员有时与包括我自己在内的Bitwise操作符混淆,只是确保没有混淆,大块代码也是如此:) +1 – RobertPitt 2010-11-18 16:51:12

0
function split_into_thirtytwos($input_array) { 
    $output_array=array(); 
    $work_array=array(); 
    $sum=0; 
    sort($input_array,SORT_NUMERIC); 
    while(count($input_array)>0) { 
    $sum=array_sum($work_array)+$input_array[count($input_array)-1]; 
    if($sum<=32) { 
     $work_array[]=array_pop($input_array); 
    } else { 
     $output_array[]=$work_array; 
     $work_array=array(); 
    } 
    } 
    if(count($work_array)>0) {$output_array[]=$work_array;} 
    return $output_array; 
} 

测试您的输入:

Array 
(
    [0] => Array 
    (
     [0] => 32 
    ) 

    [1] => Array 
    (
     [0] => 16 
     [1] => 16 
    ) 

    [2] => Array 
    (
     [0] => 8 
     [1] => 8 
     [2] => 8 
     [3] => 4 
     [4] => 4 
    ) 

) 
0
$a = array(8, 16, 16, 32, 8, 8, 4, 4); 
$group_limit = 32; 


$current_group = $result = array(); 
$cycles_since_successful_operation = 0; 

while ($a && $cycles_since_successful_operation < count($a)) 
{ 
    array_push($current_group,array_shift($a)); 

    if (array_sum($current_group) > $group_limit) 
     array_push($a,array_pop($current_group)); 
    elseif (array_sum($current_group) < $group_limit) 
     $cycles_since_successful_operation = 0; 
    elseif (array_sum($current_group) == $group_limit) 
    { 
     $result []= $current_group; 
     $current_group = array(); 
     $cycles_since_successful_operation = 0; 
    } 
} 
if ($a) 
    $result []= $a; // Remaining elements form the last group 

http://codepad.org/59wmsi4g