I have an array($data) like this.
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.80
[TOPUP_AMOUNT] => 58000.00
[TOTAL_EXPENSES] => 3114.41
)
.....
I need to get a new key called TOTAL_BALANCE
and it should get as follows,
TOTAL_BALANCE=JOINED_VALUE TOPUP_AMOUNT TOTAL_EXPENSES
Final output should look as follows,
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.80
[TOPUP_AMOUNT] => 58000.00
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 78119.39
)
.....
Can someone help me to achieve this?
Here is my try, but I am not sure this is correct or not.
$r = [];
$keys = array_keys($key1 $key2);
foreach($keys as $v){
??
}
CodePudding user response:
Do it like this:
$data = Array(
0 => Array(
'PID' => 1,
'USER_NAME' => 'JOHN',
'JOINED_DATE' => '2022-01-31',
'JOINED_VALUE' => 23233.80,
'TOPUP_AMOUNT' => 58000.00,
'TOTAL_EXPENSES' => 3114.41,
),
1 => Array(
'PID' => 2,
'USER_NAME' => 'JOHN_2',
'JOINED_DATE' => '2022-01-31',
'JOINED_VALUE' => 1234.80,
'TOPUP_AMOUNT' => 1000.00,
'TOTAL_EXPENSES' => 3114.41,
)
);
foreach($data as &$value){
// Sum and store
$value['TOTAL_BALANCE'] = $value['JOINED_VALUE'] $value['TOPUP_AMOUNT'] $value['TOTAL_EXPENSES'];
}
print_r($data);
Output:
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.8
[TOPUP_AMOUNT] => 58000
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 84348.21
)
[1] => Array
(
[PID] => 2
[USER_NAME] => JOHN_2
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 1234.8
[TOPUP_AMOUNT] => 1000
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 5349.21
)
)