将CSV结构化为对象/数组

I am using this code to import a basic CSV in which each row represents an invoice. I would like these invoices grouped by one of the columns and ultimately do a json_encode to produce a json with a parent/child hierarchy. How do I go about doing this?

CSV

 ID      CardCode    sum            amount     
 165     BENV5271    100            100 
 026     BENV5635    509.85         287.33
 9025    BENV5635    509.85         222.52  

PHP

if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
    die('Error opening file'); 
}
 $headers = fgetcsv($handle, 1024, ',');
 $cardCodes = array();

 while ($row = fgetcsv($handle, 1024, ",")) {
    $cardCodes[] = array_combine($headers, $row);
}
fclose($handle);

JSON (goal)

 [ {
 "CardCode":"BENV5271", 
 "payment_sum": "100.00"
 "details": [ {
    "DocNum": "165",
    "InvPayAmnt": "100.00",
    "PmntDate": "2012-03-29"
  } ],

}, {
 "CardCode": "BENV5635",
 "payment_sum": "509.85"
 "details": [ {
     "DocNum": "026"  
     "InvPayAmnt": "287.33",
     "PmntDate": "2012-03-29"
   }, {
     "DocNum": "025",
     "InvPayAmnt": "222.52",
     "PmntDate": "2012-03-29"
   } ],
} ]

For each $row,

@$cardCodes[$row[1]]['payment_sum'] += $row[3];
@$cardCodes[$row[1]]['details'][] = array(
    'DocNum' => $row[0],
    'InvPayAmnt' => $row[3],
    'PmntDate' => $row[4?],
);

Not exactly the same format but indexed, and good for for x in y loops in your js.