简体   繁体   English

有什么方法可以优化我的解决方案,从而实现更快,更优雅的方法?

[英]Any way to optimize my solution for a faster and more elegant approach?

In mySQL, I have a column near_to where I save entries like Public Transportation,Business center 在mySQL中,我有一列near_to ,在其中保存诸如Public Transportation,Business center类的条目

On the frontend I want to display some icons based on these entries. 在前端,我想基于这些条目显示一些图标。 For example an icon when there is Public Transportation inside the field, or Business Center or Fitness Center and so on. 例如,在场内有Public TransportationBusiness CenterFitness Center等时的图标。

This is my solution so far. 到目前为止,这是我的解决方案。 My question is, is there any way to make this faster and more elegant? 我的问题是,有什么方法可以使此操作更快,更优雅?

if (strpos($req['near_to'],'Pub') !==false) {
    echo '<li>public transportation icon</li>';
}
if (strpos($req['near_to'],'Fitn') !==false) {
    echo '<li>fitness icon</li>';
}
if (strpos($req['near_to'],'Busi') !==false) {
    echo '<li>business icon</li>';
}

I made up a little snippet with preg_replace. 我用preg_replace组成了一个小片段。 This way you can define the mapping in one array and get the final result in one statement by running preg_replace on the array itself. 这样,您可以在一个数组上定义映射,并通过在数组本身上运行preg_replace在一个语句中获得最终结果。

<?php 

$subject = "Public Transportation";
//$subject = "Business center";

$patterns = array(
    "/Pub.*/" => "<li>public transportation icon</li>",
    "/Fitn.*/" => "<li>fitness icon</li>",
    "/Busi.*/" => "<li>business icon</li>"
    );

$html = preg_replace(array_keys($patterns), array_values($patterns), $subject);

echo($html);

UPDATE if you wanna match subjects for more than one of the patterns, than the pattern key must be different. 如果您想为多个模式之一匹配主题,则更新 ,然后模式键必须不同。 The keys in the patterns array in the above example match the whole string, therefore only one icon will be returned as you said in your comment. 上例中patterns数组中的键与整个字符串匹配,因此,如您在注释中所说,将仅返回一个图标。

If we change the patterns as below, you'll see multiple icons in the html results. 如果我们按以下方式更改模式,您将在html结果中看到多个图标。 I assumed that the strings are constant and they are separated by ',', where ',' is optional, hence the '?' 我假设字符串是常量,并且用“,”分隔,其中“,”是可选的,因此“?” in the pattern. 在模式中。

<?php 

$subject = "Public Transportation,Fitness Center,Business Center"; //$subject = "Business center";

$patterns = array(
    "/Public Transportation,?/" => "<li>public transportation icon</li>",
    "/Fitness Center,?/" => "<li>fitness icon</li>",
    "/Business Center,?/" => "<li>business icon</li>"
    );

$html = preg_replace(array_keys($patterns), array_values($patterns), $subject);

echo($html);

The above will return 以上将返回

<li>public transportation icon</li><li>fitness icon</li><li>business icon</li>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM