2012-06-09 57 views
-3

假設我有一個數組生成從陣列與條件陣列

$x = (31,12,13,25,18,10); 

我想減少以這樣的方式該陣列,每個陣列元素的值是32。 所以工作後我的數組將成爲

$newx = (32,32,32,13); 

我不得不產生這種陣列以這樣的方式排列值的總和是從來沒有超過32更大。因此要創建第一個值,我將從第二個索引值12減少1,因此第二個值將變爲11,第一個索引值將變爲31+1 = 32。此過程應繼續,以便每個數組值等於32

+0

請解釋更多,因爲我不能告訴你在問什麼 - 顯示你如何找到示例 – hackartist

+0

請詳細說明。 –

+0

親愛的@ZoltanToth,可能你可以幫我解決這個問題,我已經告訴你我需要什麼。 – Aman

回答

2

這是最容易使用一些基本的數學:

$input = array(31,12,13,25,18,10); 
$val = 32;        // set the value: 32 
$sum = array_sum($input);     // calculate sum: 109 
$output = array_fill(0, $sum/$val, $val); // fill in int(109/32) = 3 reps of 32 
$rest = $sum % $val;      // however, 109*32 = 96, 
if ($rest) {        // so if there is a rest (here 13) 
    $output[] = $rest;     // we add the remaining 13 
} 

最終$output

array (
    0 => 32, 
    1 => 32, 
    2 => 32, 
    3 => 13, 
) 
+0

哦,那比我打算放的優雅多了! +1 – Lix

0

稍微更詳細的方法說明所採取的每一步 -

$x = array(31,12,13,25,18,10); 
$total = 0; 

// get the total values of the array 
foreach($x as $val){ 
    $total += $val; 
} 

// calculate whole divisions 
$divisions = floor($total/32); 

// calculate remainder 
$remainder = $total % 32; 

$finalArr = array(); 

// populate array with whole whole divisions 
for ($i=0;$i<$divisions;$i++){ 
    $finalArr[] = 32; 
} 

// last element is the remainder 
if($remainder > 0){ 
    $finalArr[] = $remainder; 
} 

輸出 -

Array 
(
    [0] => 32 
    [1] => 32 
    [2] => 32 
    [3] => 13 
)  
+1

感謝@Lix,這兩個解決方案都很成功。 – Aman