【问题标题】:if condition for array index数组索引的 if 条件
【发布时间】:2025-12-01 16:05:02
【问题描述】:
foreach($results as $result) :
 $featured_image=wp_get_attachment_url(get_post_thumbnail_id($result->ID));?>
     <div class="col-sm-6">
        <a href="javascript:;">
          <figure>
            <img src="<?php echo $featured_image ?>">
              <figcaption>
                <h2><?php echo get_the_title($result->ID) ?></h2>
                 <p><?php echo get_the_content($result->ID) ?></p>
               </figcaption>
           </figure>
        </a>
    </div>
<?php endforeach;  ?>

我想在 col-6 div 中打印前 4 个结果 其余在 col-4 中。 我正在尝试匹配数组的索引

if($results $key < 3) :
 <div class="col-sm-6"></div>
else :
<div class="col-sm-4"><div>
endif;

有什么办法可以做到这一点

【问题讨论】:

  • 你已经尝试过什么,为什么没有成功?
  • 我真的想不出办法,所以还没有尝试过任何事情
  • 但是你给出了一个伪代码示例?
  • 它不能像它一样工作它只是一个例子
  • (见下面我的回答)

标签: php arrays wordpress indexed


【解决方案1】:

只需将数组索引传入循环,然后在输出时与类名核对即可,例如:

<?php
foreach($results as $i => $result) :
$featured_image=wp_get_attachment_url(get_post_thumbnail_id($result->ID));
?>
     <div class="col-sm-<?= ($i < 4) ? 6 : 4 ?>">
        <a href="javascript:;">
          <figure>
            <img src="<?php echo $featured_image ?>">
              <figcaption>
                <h2><?php echo get_the_title($result->ID) ?></h2>
                 <p><?php echo get_the_content($result->ID) ?></p>
               </figcaption>
           </figure>
        </a>
    </div>

<?php endforeach;  ?>

【讨论】: