2017-03-02 108 views
-2

我有一個包含類似下面的數據帶列標題的CSV文件轉換CSV到鍵控JSON

100271311,90445XXXX,Active 
100271400,99456XXXX,Cancelled 
100271552,94280XXXX,Pending 

我想上面的轉換爲PHP JSON輸出像下面

{ 
    "100271311": { 
     "FIELD2": "90445XXXX", 
     "FIELD3": "Active" 
    }, 
    "100271400": { 
     "FIELD2": "99456XXXX", 
     "FIELD3": "Cancelled" 
    }, 
    "100271552": { 
     "FIELD2": "94280XXXX", 
     "FIELD3": "Pending" 
    } 
} 

請幫助

回答

0

你可以試試:

$file = file('pathtoyour/file.csv'); 
    $json = []; 
    foreach ($file as $key => $row) { 
    $cols = explode(',', $row); 
    $json[trim($cols[0])] = [ 
     'FIELD2' => trim($cols[1]), 
     'FIELD3' => trim($cols[2]), 
    ]; 
    } 
    die(json_encode($json)); 
+0

非常感謝您的快速反應 –

0

您可以試試這個:

$file = "csvfile.csv"; 
$csv = file_get_contents($file); 
$array = array_map("str_getcsv", explode("\n", $csv)); 
$json = json_encode($array); 
print_r($json); 

注: str_getcsv爲CSV格式的字段解析字符串輸入,並返回包含讀取字段的數組。

0

使用fileexplodejson_encode功能的解決方案:

$lines = file("./data/test.csv"); // change with your actual file path 
$result = []; 

foreach ($lines as $line) { 
    list($k, $f2, $f3) = explode(',', $line); 
    $result[$k] = ['FIELD2' => $f2, 'FIELD3' => trim($f3)]; 
} 

print_r(json_encode($result, JSON_PRETTY_PRINT)); 

輸出:

{ 
    "100271311": { 
     "FIELD2": "90445XXXX", 
     "FIELD3": "Active" 
    }, 
    "100271400": { 
     "FIELD2": "99456XXXX", 
     "FIELD3": "Cancelled" 
    }, 
    "100271552": { 
     "FIELD2": "94280XXXX", 
     "FIELD3": "Pending" 
    } 
} 
+0

非常感謝您的迴應,它的工作 –