首先,我知道標題是通用的並且不適合。我無法想象一個能夠描述我的問題的標題。如何優化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個不同的查詢,會更有效率嗎?我認爲可以用一個循環完成,但是我不能提出解決方案。
這隻能用一個循環完成嗎?
@pna感謝您的編輯:)當我寫這篇文章時,我幾乎睡着了。 – 2012-03-25 12:13:12