实际上我使用的是PHP framework Codeigniter,我想比较第一个foreach和第二个Codeigniter的值,但是我得到了一个错误。示例如下:
<?php foreach($posts->result() as $post): ?>
(html content)
<?php foreach($tags->result() as $tag) {
if($tag->id_users == $post->id_users) echo $tag->tag_name;
} ?>
(html content)
<?php endforeach; ?>当我比较$post->id_users内部的第二个foreach时,我得到了错误,我如何解决这个问题?
发布于 2016-09-16 13:58:36
最好避免在循环中出现循环
$tag_ids = array();
foreach($tags->result() as $tag) {
$tag_ids[] = $tag->id_users;
}
foreach ($posts->result() as $key => $post) {
if(in_array($post->id_users, $tag_ids)) {
}
}发布于 2016-09-16 03:46:02
你不会关闭第二个foreach。例如
<?php foreach($posts->result() as $post): ?> foreach1
(...some html)
<?php foreach($tags->result() as $tag) { if($tag->id_users == $post->id_users) echo $tag->tag_name; } ?> //foreach2
(...some html)
<?php endforeach; ?>
<?php endforeach; ?> 发布于 2016-09-16 13:54:37
不应该在foreach循环中使用$posts->result()和$tags->result()。因为它每次都会在foreach处于活动状态时进行检查。总的来说,它降低了脚本的性能。
<?php
$posts = $posts->result();
$tags = $tags->result();
foreach($posts as $post) {
?>
<< Other HTML code goes here >>
<?php
foreach($tags as $tag) {
if($tag->id_users == $post->id_users) {
echo $tag->tag_name;
}
?>
<< Other HTML code >>
<?php
}
}https://stackoverflow.com/questions/39518798
复制相似问题