0

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"
   } ],
} ]
8
  • you can use json_encode($row) php inbuild function Commented Jun 5, 2012 at 14:50
  • But that will not create the hierarchy.. Commented Jun 5, 2012 at 14:51
  • SO isn't about having other people write your code for you. If you want that, you need to contract someone and pay them. Commented Jun 5, 2012 at 14:53
  • @Crontab Clearly they're a noob at arrays and this is not a complex problem. Commented Jun 5, 2012 at 15:12
  • 1
    I would like to use @Bergi 's JS solution but in PHP first. stackoverflow.com/questions/10835584/… Commented Jun 5, 2012 at 15:56

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Don't you need to create the 'details' array first?
should this be inside the while loop? or should I write a new foreach loop to do this?
@Crontab This is a valid use of the error suppression operator as it only creates arrays that my not be uninitalised, and nulls where no value exists. No different from doing an isset first. For such a simple format translation, no harm is done.
@user1413248 Why would you loop through the data twice? Write to the array as you read it.
@Walf Whatever, it's lazy, that's all I'm getting at. Do it your way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.