[英]Merge datas from an array with PHP
您好,我有这个数组:
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
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'];
}
你能帮我这个忙吗?
谢谢。
这是代码:
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'];
}
}
您可以遍历数组,并使用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
)
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.