简体   繁体   English

PHP IF语句如何写得更优雅有效

[英]PHP IF Statement how can I write it more elegant and effective

I now have this code based on some of the answers below. 我现在基于以下一些答案获得此代码。

Is this the most elegant, clean, fast and effective code to have? 这是最优雅,干净,快速和有效的代码吗?

<?php
/**
 * The default template for displaying Google Analytics
 *
 * @package WordPress
 * @subpackage News_Template
 * @since News Template 1.0
 */
$googleanalyticscode="<script type='text/javascript'> var _gaq = _gaq || []; _gaq.push(['_setAccount', '%s']); _gaq.push(['_setDomainName', '%s']);   _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>";
$analyticsurlgoogle=array(
    'domain-a.com' => 'UA-25133-2',
    'domain-b.com' => 'UA-25133',
    'domain-c.com' => 'UA-2699-2',
    'domain-d.com' => 'UA-3021-2',
    'domain-e.com' => 'UA-25537-2',
    'domain-f.com' => 'UA-7213-2',
    'domain-g.com' => 'UA-7214-2',
    'domain-h.com' => 'UA-150-2',
    'domain-i.com' => 'UA-150-2'
); 
// --- /Configuration --- 
// Get the Domain URL 
$analyticsurl = get_site_url(); 
$namegoogle = substr($analyticsurl,7); 
//create code 
if (isset($analyticsurlgoogle[$namegoogle])) $code=sprintf($googleanalyticscode,$analyticsurlgoogle[$namegoogle],$namegoogle); 
else $code=''; 
echo $code; ?>

------ Previous Code ------ ------先前的代码------

I have written the following if statement in PHP. 我已经用PHP编写了以下if语句。 What would be the most elegant, effective and cleanest way of writing this code? 编写此代码的最优雅,有效和最干净的方法是什么?

The purpose of the code is to check the domain name of the site. 该代码的目的是检查站点的域名。 If the site have google analytics defined it should match the defined "Google Analytics" code for the domain and then print the script to the page. 如果网站定义了Google Analytics(分析),则该网站应与为域定义的“ Google Analytics(分析)”代码匹配,然后将脚本输出到页面。

If the Google Analytics code is not defined it should show nothing! 如果未定义Google Analytics(分析)代码,则不应显示任何内容!

<?php 
// Get the Domain URL
$analyticsurl = get_site_url();
// Check if domain is defined
if ($analyticsurl == 'http://domain-a.com') {$analyticcode = 'UA-25133920-1'; $analyticsurlname = 'domain-a.com';} // domain-a.com
if ($analyticsurl == 'http://domain-b.com') {$analyticcode = 'UA-25133920-1'; $analyticsurlname = 'domain-b.com';} // domain-b.com
if ($analyticsurl == 'http://domain-c.com') {$analyticcode = 'UA-26990264-1'; $analyticsurlname = 'domain-c.com';} // domain-c.com
if ($analyticsurl == 'http://domain-d.com') {$analyticcode = 'UA-30217571-1'; $analyticsurlname = 'domain-d.com';} // domain-d.com
if ($analyticsurl == 'http://domain-e.com') {$analyticcode = 'UA-25537388-1'; $analyticsurlname = 'domain-e.com';} // domain-e.com
// if domain is defined create Google Analytics Code and insert variables
$analyticscode_1 = "<script type='text/javascript'>
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '".$analyticcode."']);
  _gaq.push(['_setDomainName', '".$analyticsurlname."']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>";
// if URL does not match write nothing
if ($analyticcode == '') {$analyticscode = '';}
// if URL exists set the Google Analytics Code
if ($analyticcode != '') {$analyticscode = $analyticscode_1;}
?>
<?php // write the Analytics code to the page
echo $analyticscode ?>

Parse the url with parse_url (or remove the http:// part with a regexp). 使用parse_url解析网址(或使用正则表达式删除http://部分)。

Put all the codes in an array, where key is the domain name. 将所有代码放在一个数组中,其中key是域名。 Then it's a simple lookup. 然后,这是一个简单的查找。

$codes = array(
 'domain-a.com' => 'UA-25133920-1',
  //...
);
<?php

// --- Configuration ---

$template="<script type ... 
  _gaq.push(['_setAccount', '%s']);
  _gaq.push(['_setDomainName', '%s']);
  ...
</script>";

$urls=array(
 'domain-a.com' => 'UA-25133920-1',
 ...
 'domain-e.com' => 'UA-25537388-1'
);

// --- /Configuration ---

// Get the Domain URL
$url = get_site_url();
$name = substr($analyticsurl,7);

//create code
if (isset($urls[$name])) $code=sprintf($template,$urls[$name],$name);
else $code='';

// ...

echo $code;
?>

一个switch语句。

i would hold all the records in a single array so that i don't repeat the condition again and again. 我会将所有记录保存在一个数组中,这样我就不会一次又一次地重复条件。

$siteurl = get_site_url();

$analyticsurl = array(
    'http://domain-a.com' => 'UA-25133920-1', 
    'http://domain-b.com' => 'UA-25133920-1', 
    'http://domain-c.com' => 'UA-26990264-1', 
    'http://domain-d.com' => 'UA-30217571-1', 
    'http://domain-e.com' => 'UA-25537388-1'
);

if(in_array($siteurl, $analyticsurl)) {
    $analyticcode = $analyticsurl[$siteurl];
    $analyticsurlname = str_replace('http://', '', $siteurl);
}

Consider using a switch statement: 考虑使用switch语句:

switch ($analyticsurl)
{
 case: 'http://domain-a.com':
 // do some stuff
 break;

 case: 'http://domain-b.com':
 // do some stuff
 break;

 case: 'http://domain-c.com':
 // do some stuff
 break;

 case: 'http://domain-d.com':
 // do some stuff
 break;

 case 'http://domain-e.com':
 // do some stuff
 break;

 default:
 // do something by default if no match
 break;
}
<?php 

$domains['http://domain-a.com']['code'] = 'UA-25133920-1';
$domains['http://domain-a.com']['urlname'] = 'domain-a.com';
$domains['http://domain-b.com']['code'] = 'UA-25133920-1';
$domains['http://domain-b.com']['urlname'] = 'domain-b.com';
...

// Get the Domain URL
$analyticsurl = get_site_url();

// Check if domain is defined
if (array_key_exists($analyticsurl)) {
    // if domain is defined create Google Analytics Code and insert variables
?>
    <script type='text/javascript'>
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', '<?php= $domains[$analyticsurl]['code'] ?>']);
      _gaq.push(['_setDomainName', '<?php= $domains[$analyticsurl]['urlname'] ?>']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();

    </script>
<?php
}
?>

$domains['http://domain-b.com']['urlname'] = 'domain-b.com'; could be improved, because your just stripping the HTTP-part, but I was too lazy to provide a solution for that. 可以改进,因为您只剥离了HTTP部分,但是我懒得为此提供解决方案。

Use a switch block: 使用开关块:

switch ($analyticsurl) {
    case: 'http://domain-a.com' :
        $analyticcode = 'UA-25133920-1';
        $analyticsurlname = 'domain-a.com';
    break;
    default:
    break;
}

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

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