PHP foreach 嵌套循环
我有一组相册 $albums[]
和一组照片 $photos
。我想用所有匹配的照片回显每个相册,并使用以下代码:
<?php
...
foreach($albums as $album){
if( $album[photo_count] !== 0 ){
if($album[photo_count] > 10){
$limit = 10;
}
$boxID = $id = substr( $album[aid], strrpos( $album[aid], '_' )+1 );
?>
<div id="gal-<?=$boxID?>-box" class="box gallery-album">
<?
$i = 0;
foreach($photos as $photo){
if( ($photo[aid] == $album[aid]) && ($i < $limit) ){
echo '<img src="'.$photo[src_big].'" alt="'.$photo[caption].'"/>';
$i++;
}
}
?>
</div>
</div>
<?
}
}
这工作正常,但感觉非常低效。有更好的编码方法吗?
I have an array of albums $albums[]
and an array of photos $photos
. I want to echo out each album with all matching photos and am using this code:
<?php
...
foreach($albums as $album){
if( $album[photo_count] !== 0 ){
if($album[photo_count] > 10){
$limit = 10;
}
$boxID = $id = substr( $album[aid], strrpos( $album[aid], '_' )+1 );
?>
<div id="gal-<?=$boxID?>-box" class="box gallery-album">
<?
$i = 0;
foreach($photos as $photo){
if( ($photo[aid] == $album[aid]) && ($i < $limit) ){
echo '<img src="'.$photo[src_big].'" alt="'.$photo[caption].'"/>';
$i++;
}
}
?>
</div>
</div>
<?
}
}
This works fine, but feels very inefficient. Is there a better way of coding this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会担心它是否看起来高效,而是担心它是否干净且可维护。
因此,我建议您将代码分成两个函数,一个函数查找与相册关联的所有照片,另一个函数创建用于显示它的 html,例如:
您还可以使用一些 SPL 迭代器来制作代码清理器,例如
LimitIterator
,你可以用来限制传递给的数组显示给定相册的照片。I wouldn't worry about whether or not it seems efficient, but rather whether it is clean and maintainable.
As such, I would suggest you separate the code into two functions, one which finds all photos associated with an album, and one which creates the html for displaying it, e.g. something like:
You can also use some of the SPL iterators to make the code cleaner, such as
LimitIterator
, which you would use to limit the array passed to displayPhotos for a given album.嗯,这是数组的结构问题。我认为你无法以更好的方式实现这一目标。最好在 $albums 数组中的每个 album 元素中包含 photos 元素,但您必须预先解析它,这将是无用的。
Well, it's a problem of how your arrays are structured. I don't think you could achieve this in a better way. It'd be nice to have the photos element inside each album element in your $albums array, but you'd have to pre-parse it, which would be useless.