您好我有这个数组:
Array
(
[2018/03/01] => Array
(
[0] => Array
(
[BIL_Date] => 2018/03/01
[BIL_RateNonTaxed] => 105.00
[BIL_RateTaxed] => 115.500000000
[BIL_Status] => notcharged
)
[1] => Array
(
[BIL_Date] => 2018/03/01
[BIL_RateNonTaxed] => 60.00
[BIL_RateTaxed] => 63.000000000
[BIL_Status] => charged
)
[2] => Array
(
[BIL_Date] => 2018/03/01
[BIL_RateNonTaxed] => 21.00
[BIL_RateTaxed] => 25.194750000
[BIL_Status] => notcharged
)
)
)
如何合并某些数据以达到类似的效果?
我搜索按日期分组,项目charged
和notcharged
。
Array
(
[2018/03/01] => Array
(
[notcharged] => Array
(
[BIL_RateNonTaxed] => 126.00
[BIL_RateTaxed] => 140.69475
)
[charged] => Array
(
[BIL_RateNonTaxed] => 60.00
[BIL_RateTaxed] => 63.000000000
)
)
)
这是我试过的:
$datas = array();
foreach ($array as $key => $element) {
$datas[$key][] = "BIL_RateNonTaxed" => $key['BIL_RateNonTaxed'];
$datas[$key][] = "BIL_RateTaxed" => $key['BIL_RateTaxed'];
}
请你帮帮我吗?
感谢。
答案 0 :(得分:0)
以下是代码:
foreach ($array as $key => $element) {
// init every date with empty values
$datas[$key][] = [
'notcharged' => [
'BIL_RateNonTaxed' => 0,
'BIL_RateTaxed' => 0,
],
'charged' => [
'BIL_RateNonTaxed' => 0,
'BIL_RateTaxed' => 0,
],
];
// iterate over `$element`
foreach ($element as $item) {
$datas[$key][$item['BIL_Status']]['BIL_RateNonTaxed'] += $item['BIL_RateNonTaxed'];
$datas[$key][$item['BIL_Status']]['BIL_RateTaxed'] += $item['BIL_RateTaxed'];
}
}
答案 1 :(得分:0)
您可以循环访问数组并使用array_reduce
汇总数据。
$array = array
(
"2018/03/01" => array
(
array
(
"BIL_Date" => '2018/03/01',
"BIL_RateNonTaxed" => '105.00',
"BIL_RateTaxed" => '115.500000000',
"BIL_Status" => 'notcharged'
),
array
(
"BIL_Date" => '2018/03/01',
"BIL_RateNonTaxed" => '60.00',
"BIL_RateTaxed" => '63.000000000',
"BIL_Status" => 'charged'
),
array
(
"BIL_Date" => '2018/03/01',
"BIL_RateNonTaxed" => '21.00',
"BIL_RateTaxed" => '25.194750000',
"BIL_Status" => 'notcharged'
)
),
);
$result = array();
foreach ($array as $key => $element) {
$result[ $key ] = array_reduce( $element, function ($c, $v) {
if( !isset( $c[ $v["BIL_Status"] ] ) ) {
$c[ $v["BIL_Status"] ] = array(
"BIL_RateNonTaxed" => $v["BIL_RateNonTaxed"],
"BIL_RateTaxed" => $v["BIL_RateTaxed"],
);
} else {
$c[ $v["BIL_Status"] ] = array(
"BIL_RateNonTaxed" => ( $c[ $v["BIL_Status"] ]["BIL_RateNonTaxed"] + $v["BIL_RateNonTaxed"] ),
"BIL_RateTaxed" => ( $c[ $v["BIL_Status"] ]["BIL_RateTaxed"] + $v["BIL_RateTaxed"] ),
);
}
return $c;
}, array() );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
这将导致:
Array
(
[2018/03/01] => Array
(
[notcharged] => Array
(
[BIL_RateNonTaxed] => 126
[BIL_RateTaxed] => 140.69475
)
[charged] => Array
(
[BIL_RateNonTaxed] => 60.00
[BIL_RateTaxed] => 63.000000000
)
)
)