2013-12-12 19 views
0

我有一個包含以下列的表(電子郵件):在SQL循環和輸出文件中創建「塊」

date;狀態;帳戶;服務器;生日

是10,000條記錄。
我想用塊(csv文件)分隔這些記錄,每個服務器最多有50條記錄。

例如:

server1 : 13 records 
    server2 : 576 records 
    server3 : 97 records 
    server4 : 7 records 

etc 

列表1

11/12/13; 1; [email protected]; 01/01 
11/12/13; 1; [email protected]; 01/01 
11/12/13; 0; [email protected]; 01/01 
11/12/13; 1; [email protected]; 01/01 
11/12/13; 1; [email protected]; 01/01 
(Max 50 records server2 ... continues with the next server) 
11/12/13; 0; [email protected]; 01/01 
11/12/13; 0; [email protected]; 01/01 
... 

列表2

(begins at record nº 51 from Server2) 
11/12/13 0; [email protected]; 01/01 
11/12/13 0; [email protected]; 01/01 
(more 50 records from server2 ... and continues with the next server that have more than 50 records too) 
11/12/13 0; [email protected]; 01/01 
.... 

列表3

(begins at record nº 101 from server2) 
11/12/13 0; [email protected] ; 01/01 
11/12/13 0; [email protected] ; 01/01 
(more 50 records server2 ... and continues with the next server that have more than 100 records too) 
11/12/13 0; [email protected]; 01/01 
.... 

直到記錄結束。

我嘗試了很多沒有成功(同時,的foreach,做一段時間,數組,...)

對不起,我的新手問題和感謝。

回答

0

我發現了一個簡單但並不高雅的解決方案。
我創建了一個新的「導出」列,初始值爲0,循環後設置爲1。
但是...我仍然使用「F5循環」來創建下一個列表。

// Columns : email, domain, status_email, name, birthday, source, exported 

$db = new db; 

// max e-mails for domain inside the same list 
DEFINE(MAX_DOMAIN, 50); 

// I have three sources - store, e-commence, blog 
// and I need to create separate lists 
$source = "blog"; 

$filename = $source . "_" . date('Y') . date('m') . date('d') . "_" 
. date('H') . date('i') . date('s') . ".csv"; 
$fp = fopen($filename, 'a'); 
$output = "status_email;name;birthday;email\n"; 
fwrite($fp, $output); 

$sql = "SELECT distinct(domain) as domain FROM table WHERE source = $source"; 
$res = $db->sql_exec($sql); 

foreach ($res as $domain) { 
    $domain = $domain[0]; 
    $domains[$domain] = 0; 
} 

$sql = "SELECT email, domain, status_email, name, birthday 
FROM table 
WHERE exported = 0 AND source = $source"; 
$records = $db->sql_exec($sql); 

foreach ($records as $record) { 
    $email = $record[0]; 
    $domain = $record[1]; 
    $status_email = $record[2]; 
    $name = $record[3]; 
    $birthday = $record[4]; 

    if ($domains[$domain] <= MAX_DOMAIN) { 
     $domains[$domain]++; 
     $sql_update = "UPDATE table set exported = 1 
      WHERE email='$email' and domain='$domain'"; 
     $db->sql_exec($sql_update); 
     $output = "$status_email;$name;$birthday;[email protected]$domain\n"; 
     fwrite($fp, $output); 
    } 
} 
fclose($fp);