将fgetcsv响应转换为特定的json

时间:2017-06-26 11:19:38

标签: php arrays json fgetcsv

我有一个带标题的.CSV文件:

Description, BusinessSurname, IsCustomer, IsSupplier, AddressType, Business 
Address, IsInternational.

第一行:

Contact1, Contact1, True, True, Business, 123 Fake St, False

剩余的行不重要,它更像是 - 示例。我有几行数据。

我需要把它变成这种格式json:

{
Description:'Desc_47AE3208-87F5-4BBA-BE40-AA4130AB4768',
SurnameBusinessName:'Name_Business',
IsCustomer:true,
IsSupplier:true,
Addresses:
[
{AddressType:'Business',Line1:'addr1_bus',IsInternational:false},
{AddressType:'Postal',Line1:'addr1_pos',IsInternational:true}
]
}

我尝试过几种不同的方法,但是没有一种方法能够像嵌套地址那样给我一个像这样的json。我可以留下第二个地址(邮政地址)。

如果我使用此代码:

        $filename = 'contacts1.csv';
        $handle = fopen($filename, 'r');
        $count = 0;
        while (($data = fgetcsv($handle)) !== FALSE) {
            $count++;
            if ($count == 1){
                continue;
            }
        $json = json_encode($data, true);
        echo $json;
        };

我举个例子:

["Contact1","Contact1","TRUE","TRUE","Business","123 High Street Sydney NSW 2000","FALSE"]
["Contact2","Contact2","TRUE","TRUE","Business","124 High Street Sydney NSW 2000","FALSE"]
["Contact3","Contact3","TRUE","TRUE","Business","125 High Street Sydney NSW 2000","FALSE"]

有没有办法获得我需要的json,如果我无法自动获取所需的json,有没有办法可以提取每行的值,并分配给变量,并手动创建每行所需的json,使用for循环,while循环等? EG:

{
Description: $description,
SurnameBusinessName: $BusinessSurname,
etc...
}

1 个答案:

答案 0 :(得分:0)

我找到了答案,但是我已经放弃了这个API端点并且没有嵌套就更简单了。由于json格式的严格性,这个API将接受我基本上将我的csv中的每个值分配给变量并手动创建所需的json。虽然下面的代码是针对Accounts端点的,但我可以对任何端点使用完全相同的方法,因为我有点手动创建json。它是唯一可以工作的方式我认为有些字段是像AccountName这样的字符串,有些整数像AcountType。

$file = 'acc.csv';
    $mode = 'r';
    $handle = fopen($file, $mode);
    while(($csv = fgetcsv($handle)) !==FALSE){
        foreach($csv as $row => $value){
            $data = $row.$value;
            switch ($row){
                case '0':
                    $accounttype = $value;
                    break;
                case '1':
                    $accountname = $value;
                    break;
                case '2':
                    $hint = $value;
                    break;
                case '3':
                    $status = $value;
                    break;
                case '4':
                    $sortorder = $value;
                    break;
                case '5':
                    $accountcode = $value;
                    break;
                case '6':
                    $parentaccountcatid = $value;

                    $json = "
                    {
      AccountType:" . $accounttype . ",
      AccountName:'" . $accountname . "',
      Hint:'" . $hint . "',
      Status:" . $status . ",
      SortOrder:" . $sortorder . ",
      AccountCode:'" . $accountcode . "',
      ParentAccountingCategoryID:'" . $parentaccountcatid . "'
     }"; 
    //echo $json;