i want to display data in csv, now a user can have multiple loans each loan has an ID, so basically i need is count each loan_id for each user and on a single ROW display the data base on the no of the count, on thesame row if the user has another loan with a different ID do the same and display the data untill you are through with that user and move to the next row for another user like that....

//this the query
$getLoans = mysql_query("SELECT * FROM loans WHERE acctno = '$acctno'");
$loan_id = array();
$loan_acc = "";
$loan_amount = "";
while ($loanRow = mysql_fetch_assoc($getLoans)) {
$loan_id[$acctno] = $loanRow['loan_id'];
$loan_amount = $loanRow['amount'];
$loan_acc = $loanRow['acctno'];
}
$gottenAmounts2 = array();
$gottenDates2 = array();
$recordCount = array();
$loopCount = 0;
foreach ($loan_id as $acct => $lid) {
$gLive___ = mysql_query("SELECT loan_id, COUNT(*) AS live_c FROM repayments WHERE loan_id = '$lid' AND acctno = '$acct' ");
while ( $gLive___2 = mysql_fetch_assoc($gLive___)){
$recordCount[$lid] = $gLive___2['live_c'];
}
$getRe = mysql_query("SELECT * FROM repayments WHERE loan_id ='$lid' AND acctno = '$acct' ");
while ($getRes = mysql_fetch_assoc($getRe)) {
$gottenAmounts2[] = $getRes['amount'];
$gottenDates2[] = $getRes['date'];
}
}
//this the logic to display in csv,
foreach ($recordCount as $l => $rr) {
foreach ($LiveCount as $loan_acc => $kive) {
if (!isset($userData[$loan_acc])) {
$userData[$loan_acc] = array(
"NAME" => $ahafa,
"ACCOUNT NO" => $loan_acc,
"TOTAL" => $balZ_,
);
for ($i = 0; $i < $kive; $i++) {
$userData[$loan_acc]["LOAN TYPE $i"] = isset($loan_type[$i]) ? $loan_type[$i] : '';
for ($j = 0; $j < $rr; $j++) {
$userData[$loan_acc]["TRXN $i-$j"] = isset($gottenAmounts2[$j]) ? $gottenAmounts2[$j] : '';
$userData[$loan_acc]["DATE $i-$j"] = isset($gottenDates2[$j]) ? $gottenDates2[$j] : '';
}
}
}
}
}
}
the result i have is it returns the same data for each user, if user A as 3 loan_id and on each loan_id the transactions 4, 8 and 5. respectively. the loop gets the first 4 transactions and repeat the same transaction for second and third one, it dosen't go back to pick the rest only works with the first