使用 PHP 为数组中存在的每个字符串显示唯一图标的更简洁方法是什么?

What is a cleaner way to show a unique icon for each string that exists in an array using PHP?

我有一个包含以下内容的数组 $description[0]

( [0] => Time: 08:00 AM - 09:00 PM Type of Ensemble: Dueling Pianos No. of Players: 2 Additional Musicians: Yes Wedding Ceremony: Yes Cocktail Music: Yes Dinner Music: Yes Evening Entertainment: Yes DJ Services: Yes Shells: Full Projector: Yes Uplights: Yes )

我正在使用 strpos 来确定是否包含某些值,然后为每个实例显示一个唯一的图标。

我觉得这段代码真的很俗气。当然,数组可以分解为我正在检查的每件事的键。但这不是重点。

主要是想清理一下strpos函数。有没有比我下面的更简洁的方法来做到这一点?

<?php if (strpos($description[0], 'Shells: Full') !== false) { ?><img src="https://www.example.com/wp-content/uploads/2021/01/full-shells-icon.png" title="Full Shells"  /><?php   } ?>
<?php if (strpos($description[0], 'Uplights: Yes') !== false) { ?><img src="https://www.example.com/wp-content/uploads/2021/01/uplights-icon.png" title="Uplights" /><?php   } ?>
<?php if (strpos($description[0], 'Projector: Yes') !== false) { ?><img src="https://www.example.com/wp-content/uploads/2021/01/projector-icon.png" title="Projector" /><?php   } ?>
<?php if (strpos($description[0], 'Wedding Ceremony: Yes') !== false) { ?><img src="https://www.example.com/wp-content/uploads/2021/01/wedding-ceremony-icon.png" title="Wedding Ceremony" /><?php   } ?>
<?php if (strpos($description[0], 'Additional Musicians: Yes') !== false) { ?><img src="https://www.example.com/wp-content/uploads/2021/01/extra_musicians_icon.png" title="Additional Musicians" /><?php   } ?>

我会制作一个选项描述符及其相关图像的数组;然后您可以遍历数组以输出给定描述所需的所有图像:

$options = array(
    'Shells: Full' => '<img src="https://www.example.com/wp-content/uploads/2021/01/full-shells-icon.png" title="Full Shells"  />',
    'Uplights: Yes' => '<img src="https://www.example.com/wp-content/uploads/2021/01/uplights-icon.png" title="Uplights" />',
    'Projector: Yes' => '<img src="https://www.example.com/wp-content/uploads/2021/01/projector-icon.png" title="Projector" />',
    'Wedding Ceremony: Yes' => '<img src="https://www.example.com/wp-content/uploads/2021/01/wedding-ceremony-icon.png" title="Wedding Ceremony" />',
    'Additional Musicians: Yes' => '<img src="https://www.example.com/wp-content/uploads/2021/01/extra_musicians_icon.png" title="Additional Musicians" />'
);

foreach ($options as $option => $icon) {
    if (strpos($description[0], $option) !== false) {
        echo $icon;
    }
}

输出(对于您的示例输入):

<img src="https://www.example.com/wp-content/uploads/2021/01/full-shells-icon.png" title="Full Shells"  />
<img src="https://www.example.com/wp-content/uploads/2021/01/uplights-icon.png" title="Uplights" />
<img src="https://www.example.com/wp-content/uploads/2021/01/projector-icon.png" title="Projector" />
<img src="https://www.example.com/wp-content/uploads/2021/01/wedding-ceremony-icon.png" title="Wedding Ceremony" />
<img src="https://www.example.com/wp-content/uploads/2021/01/extra_musicians_icon.png" title="Additional Musicians" />

Demo on 3v4l.org