簡體   English   中英

基於另一個數組中相似值的數組值總和

[英]Sum of array values based on similar values from another array

這可能有點令人困惑,但是我將盡我所能解釋。 請多多包涵。

我有以下數組:

Array
(
    [question1] => 69
    [question2] => 36
    [question3] => 57
    [question4] => 69
    [question5] => 58
    [question6] => 40
    [question7] => 58
)

Array
(
    [question1] => 8
    [question2] => 6
    [question3] => 5
    [question4] => 6
    [question5] => 7
    [question6] => 8
    [question7] => 5
)

如您所見,兩個數組具有相同的鍵,但是每個鍵的值不同。

我需要在第二個數組中找到具有相同值的鍵,因此[question1][question6]的值均為8 然后在第一個數組中,我需要將[question1][question6]的值加在一起,因為它們在第二個數組中具有相似的值。 我需要根據第二個數組中的匹配值將第一個數組值加在一起(如果有任何意義)

理想情況下,輸出將是另一個看起來像這樣的數組:

Array
(
    [5] => 115
    [8] => 109
    [6] => 105
    [7] => 58
)

第二個數組的值成為鍵,第一個數組的相加值之和就是該值。

現在我不會在這里挑剔,因此,如果我們無法將其轉換為正確的格式,那就可以了。 我只需要能夠基於第二個數組中的相似值將第一個數組中的值加在一起。

我希望這是有道理的。 如果沒有,請發表評論,我會盡力進一步解釋。

最簡單的解決方案是遍歷第二個數組。 在第一個數組中查找鍵,如果鍵存在,則將第一個數組中的對應值添加到結果數組中,並以第二個數組中的值索引。

像這樣:

$array1 = array(
    'question1' => 69,
    'question2' => 36,
    'question3' => 57,
    'question4' => 69,
    'question5' => 58,
    'question6' => 40,
    'question7' => 58,
);
$array2 = array(
    'question1' => 8,
    'question2' => 6,
    'question3' => 5,
    'question4' => 6,
    'question5' => 7,
    'question6' => 8,
    'question7' => 5,
);

// Compose the desired result here
$result = array();

// Iterate over the second array; its values become keys in the result array
foreach ($array2 as $key => $val) {
    // If this is the first time when this value is reached then a corresponding
    // value does not yet exists in the result array; add it
    if (! isset($result[$val])) {
        $result[$val] = 0;
    }

    // Lookup the key into the first array
    if (isset($array1[$key])) {
        // If it exists then add its value to the results
        $result[$val] += $array1[$key];
    }
}

// That's all
print_r($result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM