One table called 18_7_ChartOfAccounts looks like this:
ID | AccountNumber
-------------
1 | 2310
2 | 2380
3 | 2610
Another table called 2_1_journal looks like this:
ID | Amount | DebitAccount
--------------------------
1 | 26.03 | 2310
2 | 200.00 | 2310
3 | 3.63 | 2380
4 | 119.83 | 2380
5 | 33.86 | 2610
6 | 428.25 | 2610
Aim is to get results that looks like this:
DebitAccount 2310 total is: 226.03
DebitAccount 2380 total is: 123.46
DebitAccount 2310 total is: 462.11
226.03 in this example is total of 26.03 + 200.00
At first mysql code
$query = "SELECT j.Amount, j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount)";
$sql = $db->prepare($query);
$sql->execute();
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
With print_r($data); get long list of arrays like
[31] => Array
(
[Amount] => 26.03
[DebitAccount] => 2310
[32] => Array
(
[Amount] => 200.00
[DebitAccount] => 2310
If in mysql query use SUM(j.Amount) then get only one total amount (suppose total amount of Column Amount).
With
foreach($data as $result){
if(strlen($result['Amount']) > 0 ) {
echo "Amount ". $result['Amount']. "Account name ". $result['DebitAccount']. "<br>";
print_r (array_sum($result));
}
}
Get something like this
Amount 123.97Account name 2310
2433.97Amount 26.03Account name 2310
2336.03Amount 200.00Account name 2310
Any ideas how to get necessary results (marked bold)?
Update
Changed $query to
$query = "SELECT SUM(j.Amount), j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount) group by j.DebitAccount";
with print_r($data); get array like this
Array
(
[0] => Array
(
[SUM(j.Amount)] =>
[DebitAccount] =>
)
[1] => Array
(
[SUM(j.Amount)] => 110900.16
[DebitAccount] => 2310
)
[2] => Array
(
[SUM(j.Amount)] => 3660.86
[DebitAccount] => 2380
)
With array seems all works. Now with foreach changed to
echo "Amount ". $result['SUM(j.Amount)']. " Account name ". $result['DebitAccount']. "<br>";
Get
Amount 110900.16 Account name 2310
Amount 3660.86 Account name 2380
Amount 85247.40 Account name 2610
Seems also ok. Thanks