【问题标题】:PHP: similar functionality of a jQuery $(this)?PHP:jQuery $(this) 的类似功能?
【发布时间】:2014-08-14 13:46:34
【问题描述】:

我有一个页面,我可以通过查询字符串传递一到三个变量。

分三种情况:

  • products.php?page=x
  • products.php?gender=x&page=x
  • products.php?gender=x&FILTER=x&page=x

变量pagegender 总是这样命名,但FILTER 可以是三个不同的东西:brandcategorysubcategory

因为gender 变量是可选的,所以我不能使用$_SERVER['QUERY_STRING'] 来获取它的名称和值,因为它并不总是第二个变量。

基于选择的FILTER 我做不同的事情,每个过滤器都有不同的附加功能。

我的问题是:在排除pagegender之后,我怎么知道选择了三个过滤器中的哪一个,所以基本上如果这样的事情是可能的

if ( isset($_GET['brand']) || isset($_GET['category']) || isset($_GET['subcategory']) ) {

    // $selected = whichever variable is set, something like $(this) in jQuery

}

另一种方法是为这三种情况分别创建一个if() 语句,但如果我要添加更多过滤器,那么我将不得不添加更多if() 语句。

【问题讨论】:

  • if (in_array($_GET['filter'], array('brand', 'category', 'subcategory'))?
  • 抱歉不清楚,但 filter 只是三个变量之一的占位符。所以 url 可以是 products.php?brand=1 也可以是 products.php?category=2。我需要知道变量名是什么。
  • 如果过滤器只是三个之一,为什么不使用&filter=category然后php-side switch($_GET['filter'])
  • @C.Ovidiu 循环通过$_GET?
  • 当然,您需要根据传递的过滤器运行不同的代码,所以即使我可以按照您的建议进行操作,您也需要进一步的 ifs / switch case 来处理正确的代码块。还不如只使用 ifs

标签: php if-statement query-string isset


【解决方案1】:

1) 你可以像你说的那样使用 if 语句。

2) 你可以做类似的事情

products.php?gender=x&filter=x+c&page=x

$filter = explode('+', $_GET['filter']));
$type = $filter[0] //x
$value = $filter[1] //c

然后你可以使用开关来提高可读性

switch($type){
    case 'brand':
        //do stuff
        break;
    default:
        //do stuff
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2011-02-28
    • 2012-10-04
    相关资源
    最近更新 更多