2010-11-18 211 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