2012-11-08 96 views
0

我想將CSV文件中的一行導出爲帶有require的JSON文件:CSV導出中的1行1個文件JSON。我成功導出文件,但無法過濾我想要導出的行。誰能幫我?從CSV文件導出行到JSON

<?php 

header('Content-type: application/json'); 

$feed = 'jsondata_palpad.csv'; 

$keys = array(); 
$newArray = array(); 

function csvToArray($file, $delimiter) { 
    if (($handle = fopen($file, 'r')) !== FALSE) { 
    $i = 0; 
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
     for ($j = 0; $j < count($lineArray); $j++) { 
     $arr[$i][$j] = $lineArray[$j]; 
     } 
     $i++; 
    } 
    fclose($handle); 
    } 
    return $arr; 
} 

$data = csvToArray($feed, ','); 

$count = count($data) - 1; 
$labels = array_shift($data); 


foreach ($labels as $label) { 
    $keys[] = $label; 
} 


$keys[] = 'id'; 
for ($i = 0; $i < $count; $i++) { 
    $data[$i][] = $i; 
} 


for ($j = 0; $j < $count; $j++) { 
$d = array_combine($keys, $data[$j]); 
    $newArray[$j] = $d; 
} 

//Xuat file JSON 
for ($i = 0; $i < 5; $i++) { 
    $json = json_encode($newArray[$i]); 
    echo $json . "<br />\n";  
    $filename = $data[$i][1] . ".json"; 
    echo $filename . "<br />\n"; 
    //echo "title[" . $data[$i][4] . "]"; 
    $handle = fopen("./" . $filename, "w"); 
    fwrite($handle, $json); 
    fclose($handle);  
} 

?> 

如果推薦= 2,它會輸出行id = 2。 我想導出ID,PRODUCT_ID,標題,大綱JSON文件。這個是樣品JSON文件: http://img839.imageshack.us/img839/5277/21527799.png 這是CSV文件: http://img690.imageshack.us/img690/1526/43004273.png

+0

鏈接的圖像不可用(似乎沒有網絡服務器在這些主機上運行)。 – complex857

+0

我更新的圖像,請參閱並修復它,謝謝很多複雜的 – phucloi89

回答

0

你通過所有6條線的CSV文件的循環,並將其保存以JSON文件:

for ($i = 0; $i < 5; $i++) { 
    ... 
} 

如果你知道它是什麼行數你想,通過每一行不循環 - 只需調用循環該行內的代碼。例如,如果你想第2行:

$row_we_want = 1; 
$json = json_encode($newArray[$row_we_want]); 
$filename = $data[$row_we_want][1] . ".json"; 
$handle = fopen("./" . $filename, "w"); 
fwrite($handle, $json); 
fclose($handle); 

如果你不確定它是哪一行,需要檢查每一個,你可以在迴路中這樣做:

for ($i = 0; $i < 5; $i++) { 
    if (some_condition) { 
     $json = json_encode($newArray[$i]); 
     $filename = $i][1] . ".json"; 
     $handle = fopen("./" . $filename, "w"); 
     fwrite($handle, $json); 
     fclose($handle); 
    } 
} 

而且它如果它不總是固定的長度,可能值得用循環中的數組長度替換循環中的5個數組。