PHP如何遍历关联数组并将对应字段动态输出到div指定位置
实现方案
你只需在循环的对应位置输出当前遍历到的$contact数组的对应键值即可,同时为了避免部分联系项缺失字段导致的PHP报错,建议增加字段存在性判断,修改后的完整代码如下:
<?php foreach ($array as $contact) : ?> <div class="row triangle-down ml-1 ml-sm-n1 mr-1 mr-sm-n1 bg-white contact-box"> <div class="col-12 col-md-4 contact-box-left"> <div class="col-lg-7 d-p-sm-block"> <b><?= htmlspecialchars($contact['category'] ?? '') ?></b><br/> </div> </div> <div class="col-12 col-md-8"> <div class="row pl-2 pr-3 contact-box-right"> <div class="col-lg-7 d-p-sm-block"> <p> <?php if (!empty($contact['company'])): ?> <b><?= htmlspecialchars($contact['company']) ?></b><br/> <?php endif; ?> <?php if (!empty($contact['companyName'])): ?> <?= htmlspecialchars($contact['companyName']) ?><br/> <?php endif; ?> <?php if (!empty($contact['address'])): ?> <?= htmlspecialchars($contact['address']) ?><br/> <?php endif; ?> <?php if (!empty($contact['city'])): ?> <?= htmlspecialchars($contact['city']) ?><br/> <?php endif; ?> <?php if (!empty($contact['phoneNumber'])): ?> <?= htmlspecialchars($contact['phoneNumber']) ?><br/> <?php endif; ?> <?php if (!empty($contact['fax'])): ?> <?= htmlspecialchars($contact['fax']) ?><br/> <?php endif; ?> <?php if (!empty($contact['website'])): ?> <a href="<?= htmlspecialchars($contact['website']) ?>">Website</a> <?php endif; ?> </p> </div> <div class="col-lg-5 contact-button"> <a href="javascript:void(0)" class="btn-sm btn-button btn-contact">Kontaktformular</a> </div> </div> </div> </div> <?php endforeach; ?>
关键说明
- 代码中使用
??空合并运算符判断字段是否存在,避免PHP抛出「Undefined array key」类的错误提示 - 使用
htmlspecialchars()对输出内容做转义处理,规避XSS跨站脚本攻击风险 - 对于非必填的可选字段(如company、address等),额外增加了非空判断,字段为空时不会输出对应行,不会在页面上留下多余空行
内容的提问来源于stack exchange,提问作者strayed soul
相关产品推荐
相关产品推荐

