【发布时间】:2017-11-30 13:35:31
【问题描述】:
如何从 csv 文件中获取此 json。 csv 文件具有标题:
Description, BusinessSurname, IsCustomer, IsSupplier, AddressType, BusinessAddress, IsInternational
第一行:
Contact1, Contact1, True, True, Business, 123 Fake St, False
我需要将 csv 中的数据转换为确切的 json,但需要它循环以查找可能存在的任何其他行。
{
Description:'Contact1',
SurnameBusinessName:'Contact1',
IsCustomer:True,
IsSupplier:True,
Addresses:
[
{AddressType:'Business',Line1:'123 Fake St',IsInternational:False},
]
}
我不能让它工作。请帮忙。
########################################
我找到了这个问题的答案,在尝试了所有可能的解决方案后,我意识到我必须手动创建 json,因为没有 json 或数组可以完全满足我的需求。然而,我已经放弃了这个 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;
【问题讨论】:
-
“我想要adfasdgfasdf” - 嗯?
标签: php arrays json csv fgetcsv