创建用于XML导出的多维对象 [英] Creating a multidimensional object for XML export

查看:90
本文介绍了创建用于XML导出的多维对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在导入包含大量发票数据的csv文件.需要根据供应商ID将这些数据分组在一起,以显示每个供应商的标题以及该供应商ID的所有发票的总和;然后在其下方显示每个单独的发票.该项目的目标是导入CSV,向用户显示数据,允许通过选择框更改某些值,然后单击一个按钮即可将其导出为XML. XML的结构与HTML相似,其中每组发票首先显示某些通用数据,然后在下面显示汇款数据.为实现此目的,我正在尝试使用一种 http://goessner.net/download/prj/jsonxml/.

I am importing a csv file which has a lot of invoice data. This data needs to be grouped together based on Vendor ID to display a heading for each Vendor with a sum of all invoices for that Vendor Id; and also then display each individual invoice below it. The goal of this project is to import the CSV, display the data to the user, allow for certain values to be changed via select boxes, and then at a click of a button export to XML. The XML is structured in a similar way as the HTML where by each group of invoices has certain common data displayed at first and then the remittence data is below. To achieve this, I am trying to structure the Object in a way to help me convert it properly to XML using this http://goessner.net/download/prj/jsonxml/ .

问题:后两笔付款需要组合在一起,我希望为每行详细数据创建一个数组,然后将其添加到主对象的PmtDetail属性中.目前,此代码仅广告第一行,而忽略其余行.

Problem: The second two payments need to be grouped together and I would like an array to be created for each row of detailed data and then be added to the main object into the PmtDetail attribute. At the moment this code only ads the first row and ignores the rest.

CSV代码段(我此处不包括代码中正在使用的所有行)

CSV Snippet (I am not including all the rows that are being used in the code here)

 ID         CardCode   payment_sum    amount     
 1610165    BENV5271    100            100 
 1609026    BENV5635    509.85         287.33
 1609025    BENV5635    509.85         222.52 

JSON

 [{"DocNum":"1610165","CardCode":"BENV5271","InvPayAmnt":"100.00","PmntDate":"2012-03-29","payment_sum":"100.00"},
 {"DocNum":"1609026","CardCode":"BENV5635","InvPayAmnt":"287.33","PmntDate":"2012-03-29","payment_sum":"509.85"},  
 {"DocNum":"1609025","CardCode":"BENV5635","InvPayAmnt":"222.52","PmntDate":"2012-03-29","payment_sum":"509.85"}]

jQuery

 $(document).ready(function() {
    $.getJSON('CSV.php', function(data) {

    var prevCardCode = '';
    var newDiv; var NewDiv2;
var PaymentFormat;

    $.each(data, function(index, element) { //looping once to display header info such as sum
        XMLObject = []; // Creating a new object for each row     

        if (element['CardCode'] != prevCardCode) {

            XMLObject.Vendor_Sum = element['payment_sum'];
            XMLObject.Name1 = element['CardName'];
            XMLObject.Addr1 = element['Address'];

            console.log(XMLObject);

            newDiv = $('<div/>').addClass('row').appendTo('#showdata');
            $('<div class="sum_field">' + 'Total: ' + element['payment_sum'] + '</div>').appendTo(newDiv);

                $('<div class="options">Payment Format: <select name="Payment_Format" id="Payment_Format"><option value="CTX" selected="selected">Company to Company</option><option value="PPD">Company to Person</option></select> </div><div id="Selected_Format"></div>').appendTo(newDiv);

                XMLObject.paymentFormat = $('select#Payment_Format').val();;

                $('select#Payment_Format').change(function(){
                    PaymentFormat = $(this).val();
                    XMLObject.paymentFormat = PaymentFormat;
                });

        }

        newDiv2 = $('<div/>').addClass('sub_row').appendTo(newDiv);

        prevCardCode = element['CardCode'];

        $.each(element, function(key, value) { looping 2nd time to display the detail info
            XMLObjectDetail = {};   // Creating an array for each row of detail info

            XMLObjectDetail['TotalCurAmount'] = element['InvPayAmnt']; 
            XMLObjectDetail['NetCurAmount'] = element['InvPayAmnt'];

                   $('<div class="field">' + value + '</div>').appendTo(newDiv2);
                   XMLObject.PmtDetail =  XMLObjectDetail;
             });      
         });
     });
  });

PHP

 <?php 
  if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
    die('Error opening file'); 
 }

 $headers = fgetcsv($handle, 1024, ',');
 $complete = array();

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

    echo json_encode($complete);

?>

推荐答案

一些想法:

  • $.each(data, ... //looping once to display header info such as sum您没有在任何地方创建总和.另外,这是唯一循环遍历所有data行的循环.
  • XMLObject = []; // Creating a new object for each row-不,您正在创建一个数组.您确实应该创建一个对象({}),因为您将其用作对象.
  • XMLObject =....您这里缺少var关键字.您每次迭代都创建一个新对象,但是将每个对象分配给相同的全局变量.这就是#Payment_Format更改处理程序将仅更改最后创建的对象(当前由"XMLObject"引用的对象)的格式的原因.
  • $('...<select name="Payment_Format" id="Payment_Format">...')您正在使用每次迭代创建一个带有 id 的选择.您如何看待ID是唯一的?这也是('select#Payment_Format')将不选择当前迭代中创建的元素的原因.
  • $.each(element... looping 2nd time to display the detail info否.这不是第二个循环,而是一个将迭代当前element属性的循环-该循环将应用于每个迭代的data行.
  • XMLObjectDetail = {}; // Creating an array for each row of detail info-不,您正在创建一个对象.同样,您缺少var关键字.
  • (编辑)XMLObject.PmtDetail = XMLObjectDetail;-您在此处每次元素迭代都会覆盖"PmtDetail"属性.那不是您要附加的数组吗?
  • 在循环代码的最后,您有一个XMLObject,其中包含有关当前行的数据.您是否不想使用它,例如将其推到行对象数组上?
  • $.each(data, ... //looping once to display header info such as sum You're not creating a sum anywhere. Also, this is the one and only loop that iterates over all data rows.
  • XMLObject = []; // Creating a new object for each row - No, you're creating an Array. You really should create an Object ({}), because you use it as an object.
  • XMLObject =.... You're lacking a var keyword here. You create a new object each iteration, but assign every of them to the same global variable. This is the reason the the #Payment_Format change handler will only change the format of the last created object - the one currently referenced by "XMLObject".
  • $('...<select name="Payment_Format" id="Payment_Format">...') You are creating a select with an id each iteration. How do you think that id will be unique? That's also why ('select#Payment_Format') will select not the element created in the current iteration.
  • $.each(element... looping 2nd time to display the detail info No. This is not a second loop, but a loop which will iterate over the properties of the current element - the loop will be applied on each of the iterated data-rows.
  • XMLObjectDetail = {}; // Creating an array for each row of detail info - No, you're creating an object. Again, you're missing the var keyword.
  • (edit) XMLObject.PmtDetail = XMLObjectDetail; - you overwrite the "PmtDetail" property each iteration of elements in here. Shouldn't that be an array you append to?
  • At the end of the loop code you have a XMLObject, containing data about the current row. Don't you want to do something with it, for example push it onto an array of row-objects?

好的,我想现在我正在获得您想要实现的目标.合适的结构可能是:

OK, I think now I'm getting what you try to achieve. An appropriate structure might be:

[ {
    "CardCode":"BENV5271"
    "details": [ {
        "DocNum": "1610165",
        "InvPayAmnt": "100.00",
        "PmntDate": "2012-03-29"
      } ],
     "payment_sum": "100.00"
   }, {
     "CardCode": "BENV5635",
     "details": [ {
         "DocNum": "1609026"  
         "InvPayAmnt": "287.33",
         "PmntDate": "2012-03-29"
       }, {
         "DocNum": "1609025",
         "InvPayAmnt": "222.52",
         "PmntDate": "2012-03-29"
       } ],
     "payment_sum": "509.85"
    } ]

或相同,就像id一样的对象(键-值映射):

or the same, just as an Object (key-value-map) by id:

{
    "BENV5271" : {
        "details": {
            "1610165": {
                 "InvPayAmnt": "100.00",
                 "PmntDate": "2012-03-29"
             }
         }
         "payment_sum": "100.00"
     },
     "BENV5635": {
         "details": {
             "1609026": {
                 "InvPayAmnt": "287.33",
                 "PmntDate": "2012-03-29"
             },
             "1609025": {
                 "InvPayAmnt": "222.52",
                 "PmntDate": "2012-03-29"
             }
        },
        "payment_sum": "509.85"
    }
}

您还可以将JSON的数字类型用于数字值,而不是字符串:-)您应该立即从数据库中创建该结构.如您所见,CSV并不是最好的表示形式,并且由于JSON和XML能够表示它,因此您不应该使用SQL-> CSV-> JSON(表)-> JSON(结构化)-> XML,而应该使用SQL- > JSON(结构化)-> XML或什至更好的是SQL-> XML.您可以使用Ajax轻松读取XML并在JavaScript中更改其DOM.

You also might use the number type of JSON for number values, instead of string :-) You should create that structure right away from your database. As you have seen, CSV is not the best representation for it, and as JSON and XML are capable of representing it you should not go SQL->CSV->JSON(table)->JSON(structured)->XML but SQL->JSON(structured)->XML or even better right away SQL->XML. You can easily read XML with Ajax and change its DOM in JavaScript.

如果您真的需要将格式错误的对象重组为JS中的一个不错的结构,则代码如下:

If you really need to do the restructuring from malformed Objects to a nice structure in JS, this would be the code:

var cards = {}; // an object indexed by the CardCodes;
for (var i=0; i<data.length; i++) { // loop through the received JSON
    // data[i] equals the "element" variable from your code
    var code = data[i].CardCode;
    if (! code in cards) { // there is no card with that code
        cards[code] = {
            vendorSum: data[i].payment_sum,
            name: data[i].CardName,
            addr: data[i].Address,
            ...
            pmtDetail: [] // create array for the details
        };
    } // else: element already created
    cards[code].pmtDetail.push({
        docNum: data[i].DocNum, 
        amount: data[i].InvPayAmnt
        ...
    }); // adds a new detail object to the array
}

这篇关于创建用于XML导出的多维对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆