foreach 嵌套在 foreach 中,我可以提高效率吗?
我有一个字母数组,用于创建标题并对数据库中的 listItems 数组进行排序。我现在所拥有的是:
$alph = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
foreach($alph as $data) {
echo "<h3 id=" . $data .">" . $data . "</h3><br />";
foreach($list as $listItem) {
if(strtolower(substr($listItem->title, 0, 1)) === $data) {
echo $listItem;
}
}
}
这很有效,但我觉得可能可以进行改进以提高速度。
I have an array of letters that are used to create a header and sort an array of listItems from my database. What i have right now is:
$alph = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
foreach($alph as $data) {
echo "<h3 id=" . $data .">" . $data . "</h3><br />";
foreach($list as $listItem) {
if(strtolower(substr($listItem->title, 0, 1)) === $data) {
echo $listItem;
}
}
}
This works great but I feel there may be improvements that can be made to increase speed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该首先循环遍历具有最长索引的数组,在大多数语言中,外循环索引增加最快。
此外,只要每个项目知道它应该具有什么类型的标题,就不需要循环遍历标题。
You should loop through the array with the longest index first, in most languages the outer loop index increases the quickest.
Also there is no need to loop through the headers as long as each item knows what type of header it should have.
在开始之前对 $list 进行排序。这样您就可以获得实现的排序算法的效率(在 PHP 中,它是快速排序,它的性能比您当前的解决方案好得多)。
Sort $list before you start. That way you get the effiency of the implemented sorting algorithm (in PHP, it's quicksort, which performs a lot better than your current solution).
单循环,更灵活的首字符逻辑:
Single loop, and more flexible first-character logic:
我认为解决方案是 O(n),但使用 php 哈希数组作弊:
Solution that is O(n) i think, but cheats with php hash arrays: