foreach ($summary as $split) {
if (isset($split['currency'])) {
if (!isset($result[$split['currency']]) {
$result[$split['currency']] = [
'duration' => 0,
'cost' => 0
];
}
$result[$split['currency']]['employee'] = $split['employee'];
$result[$split['currency']]['duration'] += $split['duration'];
$result[$split['currency']]['cost'] += $split['cost'];
} else {
$result[0]['employee'] = $split['employee'];
$result[0]['duration'] += $split['duration'];
$result[0]['cost'] += $split['cost'];
}
}
我的数组看起来像这样
$summary = Array
(
[0] => Array
(
[employee] => John
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[1] => Array
(
[employee] => Fil
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[2] => Array
(
[employee] => John
[currency] =>
[duration] => 8.00
[cost] =>
)
[3] => Array
(
[employee] => John
[currency] => MYR
[duration] => 12.00
[cost] => 342.86
)
[4] => Array
(
[employee] => Sam
[currency] => SGD
[duration] => 8.00
[cost] => 228.57
)
[5] => Array
(
[employee] => Fil
[currency] => MYR
[duration] => 12.00
[cost] => 342.86
)
我想按员工和货币对上述数组进行分组。我需要的是Stackoverflow
但是这个分组仅用于货币,所以在输出数组中只有3个内部数组。
我想对数组进行分组,以便结果将第一个员工和货币分组。因此每位员工将有3个内部数组
答案 0 :(得分:1)
只需在货币键<$ p>之前的$ result数组中添加名称作为键
foreach ($summary as $split) {
if (isset($split['currency'])) {
if (!isset($result[$split['employee']][$split['currency']]) {
$result[$split['employee']][$split['currency']] = [
'duration' => 0,
'cost' => 0
];
}
$result[$split['employee']][$split['currency']]['employee'] = $split['employee'];
$result[$split['employee']][$split['currency']]['duration'] += $split['duration'];
$result[$split['employee']][$split['currency']]['cost'] += $split['cost'];
} else {
$result[0]['employee'] = $split['employee'];
$result[0]['duration'] += $split['duration'];
$result[0]['cost'] += $split['cost'];
}
}
答案 1 :(得分:0)
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$in = [
['employee'=>'A','currency'=>'USD','duration'=>8.00,'cost'=>42]
,['employee'=>'A','currency'=>'SDU','duration'=>8.00,'cost'=>42]
,['employee'=>'A','currency'=>'','duration'=>8.00,'cost'=>42]
,['employee'=>'B','currency'=>'USD','duration'=>8.00,'cost'=>42]
,['employee'=>'B','currency'=>'SDU','duration'=>8.00,'cost'=>42]
,['employee'=>'B','currency'=>'','duration'=>8.00,'cost'=>42]
];
$result = [];
$groupSum = function ($v) use (&$result) {
$emp = $v['employee'];
$curr = $v['currency'];
if ( !array_key_exists($emp,$result) ) {
$result[$emp] = [];
}
if ( !array_key_exists($curr,$result[$emp]) ) {
$result[$emp][$curr] = ['duration'=>0,'cost'=>0];
}
$result[$emp][$curr]['duration'] += $v['duration'];
$result[$emp][$curr]['cost'] += $v['cost'];
};
array_map($groupSum,$in);
print_r($result);