我怎样才能把它放在for循环中?

时间:2020-03-17 06:30:47

标签: php for-loop

我想清理此问题并将其放入for循环中,“因为我有更多的国家/地区,但成功并不多...有人可以帮忙吗?

if (strpos($_SERVER['REQUEST_URI'], "hr") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/hr.php';

}
else if (strpos($_SERVER['REQUEST_URI'], "hu") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/hu.php';

}

else if (strpos($_SERVER['REQUEST_URI'], "it") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/it.php';

}

else if (strpos($_SERVER['REQUEST_URI'], "ro") !== false){
include '/var/www/sites/footer/zohomerce/include/rabaho/tos/ro.php';

}

2 个答案:

答案 0 :(得分:1)

您可以创建一个包含国家/地区代码的数组,并在其中循环查找匹配项

$array = array('hu', 'it', 'ro', 'hr');

foreach( $array as $country ) {
    if ( strpos($_SERVER['REQUEST_URI'], $country ) !== false ){
       include '/var/www/sites/footer/zohomerce/include/rabaho/tos/' . $country . '.php';
       break;
    }
}

如果URI为http://homesite.com,它将包含'it'并且将强制提供错误的搜索结果。 因此,如果URI类似于http://homesite.com/it/page.php,则需要搜索/it/而不是it

答案 1 :(得分:0)

作者仅检查价值存在的想法是有缺陷的。如果URL包含值但语义不同,该怎么办?

我建议同时看一下位置和语言。

// Explode the url into parts
$urlParts = explode('/',$_SERVER['REQUEST_URI']);

// allowed values
$array = ['hu', 'it', 'ro', 'hr'];

// here I assume that language will always be in the 1st position
// e.g. yoursite.com/hu/whatever
//      yoursite.com/it
// if value is not provided, use hu
$countryStr = isset($urlParts[1]) ? $urlParts[1] : 'hu';

// Checking if value is within allowed values to prevent nasty stuff
if ($countryStr, $array) 
{
    include '/var/www/sites/footer/zohomerce/include/rabaho/tos/' . $countryStr . '.php';
}

如果您将值作为URL参数传递,则还有$_GET[]数组