簡體   English   中英

PHP匯總其他字段來自數組中的唯一ID

[英]PHP sum by other field from unique id in array

我有一個像這樣的多維數組:

Array
(
    [0] => array('id'=>1,'name'=>'Agent 1','total'=>3)
    [1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
    [2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
    [3] => array('id'=>1,'name'=>'Agent 1','total'=>6)
)

我想從這個數組中刪除重復的代理,並將total字段total到最終的數組,如下所示:

Array
(
    [0] => array('id'=>1,'name'=>'Agent 1','total'=>9)
    [1] => array('id'=>2,'name'=>'Agent 2','total'=>3)
    [2] => array('id'=>3,'name'=>'Agent 3','total'=>3)
)

我嘗試過array_unique但它只刪除重復...

試試這段代碼: 沙盒代碼
算法的主要思想 - 在結果數組中緩存密鑰對並進一步檢查它們的存在。

$array = [
    0 => ['id' => 1, 'name' => 'Agent 1', 'total' => 3],
    1 => ['id' => 2, 'name' => 'Agent 2', 'total' => 3],
    2 => ['id' => 3, 'name' => 'Agent 3', 'total' => 3],
    3 => ['id' => 1, 'name' => 'Agent 1', 'total' => 6],
];

$sumArray = [];

foreach ($array as $agentInfo) {

    // create new item in result array if pair 'id'+'name' not exists
    if (!isset($sumArray[$agentInfo['id'].$agentInfo['name']])) {
        $sumArray[$agentInfo['id'].$agentInfo['name']] = $agentInfo;
    } else {
        // apply sum to existing element otherwise
        $sumArray[$agentInfo['id'].$agentInfo['name']]['total'] += $agentInfo['total'];
    }
}

// optional action to flush keys of array
$sumArray = array_values($sumArray);

print_r ($sumArray);

試試這個,

$arrays = array_values(array_combine(array_map(function ($i) { return $i['id']; }, $array), $array));    
print_r($arrays);

DEMO

為了獲得您想要的精確輸出,您將需要一個嵌套循環。

$input = array(
    0 => array('id'=>1,'name'=>'Agent 1','total'=>3),
    1 => array('id'=>2,'name'=>'Agent 2','total'=>3),
    2 => array('id'=>3,'name'=>'Agent 3','total'=>3),
    3 => array('id'=>1,'name'=>'Agent 1','total'=>6)
);
// This is where we will save our result
$output = array();

foreach ($input as $item) {
    // Used to determine if the current $item 
    // already exists in the $output array
    $foundItem = false;
    // Now we check the $item against every output entry
    foreach ($output as &$entry) {
        if ($entry["id"] == $item["id"]) {
            // Since we found a match, let's add the 
            //current item's total to the output total.
            $entry["total"] += $item["total"];
            // Marking this as true will later prevent us 
            // from inserting the item to the output array twice
            $foundItem = true;
        }
    }
    // If the item was not found in the output array
    // the $foundItem variable remains false
    // Using ! to negate the boolean, we insert the item to the output array
    if (!$foundItem) {
        $output[] = $item;
    }
}

意識到這不是獲得所需輸出的唯一方法。 這只是最簡單的解決方案,當然可以通過多種方式進行改進。 但是,我會把那部分留給你。

假設id是唯一的,你可以使用它

$array = array(
    array('id' => 1, 'name' => 'Agent 1', 'total' => 3),
    array('id' => 2, 'name' => 'Agent 2', 'total' => 3),
    array('id' => 3, 'name' => 'Agent 3', 'total' => 3),
    array('id' => 1, 'name' => 'Agent 1', 'total' => 6)
);
$array_ids = array();

foreach ($array as $key => $value) {
    if (isset($array_ids[$value['id']])) {
        $array[$array_ids[$value['id']]]['total'] += $value['total'];
        unset($array[$key]);
    }
    else
    {
        $array_ids[$value['id']] = $key;
    }
}

通過這種方式,您可以將使用過的id保存到數組$ array_ids中,您可以輕松檢查數組中是否已存在代理

我嘗試使用array_reduce - 使用回調函數迭代地將數組減少為單個值。 並根據要求編寫了一個功能。 希望這會幫助你。

<?php   
$array = [
    0 => ['id' => 1, 'name' => 'Agent 1', 'total' => 3],
    1 => ['id' => 2, 'name' => 'Agent 2', 'total' => 3],
    2 => ['id' => 3, 'name' => 'Agent 3', 'total' => 3],
    3 => ['id' => 1, 'name' => 'Agent 1', 'total' => 6],
    ];

$result = array_reduce($array, function($temp, $item){
    isset($temp[$item['id']])
       ? $temp[$item['id']]['total'] += $item['total']
       : $temp[$item['id']] = $item;
    return $temp;
}, []);

print_r($result);
?>

OUTPUT

排列

[1] =>數組([id] => 1 [名稱] =>代理1 [總] => 9)

[2] =>數組([id] => 2 [名稱] =>代理2 [總] => 3)

[3] =>數組([id] => 3 [名稱] =>代理3 [總] => 3)

暫無
暫無

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

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