2012-03-24 102 views
-2

首先,我知道標題是通用的並且不適合。我無法想象一個能夠描述我的問題的標題。如何優化PHP中的foreach循環

我有MySQL中的表結構收件人像這樣:

id | email | status 
1  [email protected]   S 
2  [email protected]   S 
3  [email protected]   R 
4  [email protected]   B 

我需要將數據轉換成以下XML,這取決於狀態場。例如:

<Recipients> 
    <RecipientsSent> 
     <!-- Have the 'S' status --> 
     <recipient>[email protected]</recipient> 
     <recipient>[email protected]</recipient> 
    </RecipientsSent> 

    <RecipientsRegexError> 
     <recipient>[email protected]</recipient> 
    </RecipientsRegexError> 

    <RecipientsBlocked> 
     <recipient>[email protected]</recipient> 
    </RecipientsBlocked> 
</Recipients> 

我有這樣的PHP代碼來實現這一點($收件人包含db表的關聯數組):

<Recipients> 

<RecipientsSent> 
<?php 
foreach ($recipients as $recipient): 
    if ($recipient['status'] == 'S'): 
     echo "<recipient>" . $recipient['email'] . "</recipient>"; 
    endif; 
endforeach; 
?> 
</RecipientsSent> 

<RecipientsRegexError> 
<?php 
foreach ($recipients as $recipient): 
    if ($recipient['status'] == 'R'): 
     echo "<recipient>" . $recipient['email'] . "</recipient>"; 
    endif; 
endforeach; 
?> 
</RecipientsRegexError> 
<?php /** same loop for the B status */ ?> 

</Recipients> 

因此,這意味着如果我有1000項表格和4種不同的狀態',可以檢查,這意味着會有4個循環,每個執行1000次。

這怎麼能以更有效的方式完成?我想過從數據庫中提取四組不同的數據庫,這意味着4個不同的查詢,會更有效率嗎?我認爲可以用一個循環完成,但是我不能提出解決方案。

這隻能用一個循環完成嗎?

回答

0

有了一個循環,你可以做以下

<?php 

$string1, $string2 = ''; 

foreach ($recipients as $recipient) { 
    $recipient_email = "<recipient>" . $recipient['email'] . "</recipient>"; 

    switch($recipient['status']) { 
    case 'a': 
     $string1 .= $recipient_email; 
     break; 
    case 'b': 
     $string2 .= $recipient_email; 
     break; 
    } 
} 
?> 

<Recipients> 
    <RecipientsSent> 
    <?php echo $string1; ?> 
    </RecipientsSent> 
    <RecipientsRegexError> 
    <?php echo $string2; ?> 
    </RecipientsRegexError> 
</Recipients> 
+0

@pna感謝您的編輯:)當我寫這篇文章時,我幾乎睡着了。 – 2012-03-25 12:13:12

0

爲什麼不只是讓您的收件人循環一次,並將其分配給4個列表中的一個(每個狀態一個)。然後,您只需遍歷每個列表即可生成XML。

儘管只有4種狀態並沒有多大好處。 (雖然,你居然異形你的代碼,看看這是否需要優化?)

+1

Downvoter:保健評論? – 2012-03-24 22:51:43