2017-02-12 28 views
0

我一直在這裏工作了一段時間,似乎無法找到解決方案。尋找從數組中提取數值的方法,將它們添加並推送到新陣列

我開始有一個這樣的數組:

[ 
    [ 
     'username' => 'test', 
     'amount' => 1.05 
    ], 
    [ 
     'username' => 'test', 
     'amount' => 2.05 
    ], 
    [ 
     'username' => 'test', 
     'amount' => 3.05 
    ], 
    [ 
     'username' => 'demo', 
     'amount' => 4.10 
    ], 
    [ 
     'username' => 'demo', 
     'amount' => 4.10 
    ], 
    [ 
     'username' => 'demo', 
     'amount' => 2.10 
    ] 
] 

而且我最終尋求與像這樣的陣列來結束:

[ 
    [ 
     'username' => 'test', 
     'total' => 6.15 
    ], 
    [ 
     'username' => 'demo', 
     'total' => 10.30 
    ] 
] 

正如你所看到的,我想提取每個用戶的金額值,將其添加並使用用戶名和總金額累加到新陣列。

有關如何實現此目的的任何想法?

回答

0

因此,您可以簡單地遍歷數組的每個元素並以Array['username']['total']的形式填充多維關聯數組。

function sumByUsername($array) 
{ 
    foreach ($array as $item) { 
     $output[$item['username']]['total'] += $item['amount']; 
    } 

    return $output; 
} 

所以在使用您的測試數據:

$output = sumByUsername($input); 
var_dump($output); 

你會得到這樣一個數組:

// array(2) { 
//  ["test"]=> 
//  array(1) { 
//   ["total"]=> 
//  float(6.15) 
//  } 
//  ["demo"]=> 
//  array(1) { 
//   ["total"]=> 
//  float(10.3) 
//  } 
// } 

爲了讓你指定的確切輸出,下面一行添加到循環:

function sumByUsername($array) 
{ 
    foreach ($array as $item) { 
     $output[$item['username']]['username'] = $item['username']; // <----- 
     $output[$item['username']]['total'] += $item['amount']; 
    } 
} 

// array(2) { 
//  ["test"]=> 
//  array(2) { 
//   ["username"]=> 
//  string(4) "test" 
//   ["total"]=> 
//  float(6.15) 
//  } 
//  ["demo"]=> 
//  array(2) { 
//   ["username"]=> 
//  string(4) "demo" 
//   ["total"]=> 
//  float(10.3) 
//  } 
// } 
+0

這確實解決了我的問題,謝謝你ü! – savage

相關問題