[英]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.