所以我有一堆混乱的代码,我确信有更简洁的方法可以解决这个问题。基本上我有一个包含多个变量的url。根据变量设置其他变量。下面的代码按预期运行,只是尝试找到更清晰的路径。
$sortby = $_GET['sort'] or $sortby = 'price';
$direction = $_GET['dir'] or $direction = 'desc';
$automake = $_GET['make'] or $automake = '';
$autocat = $_GET['model'] or $autocat = '';
$searchkey = $_GET['s'] or $searchkey = '';
$autocondition = $_GET['cond'] or $autocondition = '';
if ($sortby == 'price') { $sorting = '_auto_price'; $orderby = 'meta_value_num'; }
else if ($sortby == 'year') { $sorting = '_auto_year'; $orderby = 'meta_value'; }
else if ($sortby == 'make') { $sorting = '_auto_make'; $orderby = 'meta_value'; }
else if ($sortby == 'model') { $sorting = '_auto_model'; $orderby = 'meta_value'; }
else { $sorting = ''; $model = ''; $orderby = 'date'; }
然后我会显示一些链接来设置新变量。如果您还没有猜到这些是对页面内容进行排序的不同方法。这些也很丑陋。他们再次工作,只是不太漂亮。
<ul class="breadcrumb">
<li><strong>SORT BY:</strong></li>
<li style="padding:0 3px;"></li>
<li>Price:
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=price&dir=asc&cond=<?php echo $autocondition ?>">UP</i></a>
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=price&dir=desc&cond=<?php echo $autocondition ?>">DOWN</i></a>
</li>
<li style="padding:0 3px;"></li>
<li>Year:
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=year&dir=asc&cond=<?php echo $autocondition ?>">UP</a>
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=year&dir=desc&cond=<?php echo $autocondition ?>">DOWN</a>
</li>
<li style="padding:0 3px;"></li>
<li>Make:
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=make&dir=asc&cond=<?php echo $autocondition ?>">UP</i></a>
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=make&dir=desc&cond=<?php echo $autocondition ?>">DOWN</a>
</li>
<li style="padding:0 3px;"></li>
<li>Model:
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=model&dir=asc&cond=<?php echo $autocondition ?>">UP</i></a>
<a href="/inventory?s=<?php echo $searchkey ?>&make=<?php echo $automake ?>&model=<?php echo $autocat ?>&sort=model&dir=desc&cond=<?php echo $autocondition ?>">DOWN</a>
</li>
</ul>
答案 0 :(得分:1)
一种方法是将所有值存储在数组中并获取相应的值
$parameters["price"]=array("sort_by"=>"_auto_price","order_by"=>"meta_value_num");
$parameters["year"] =array("sort_by"=>"_auto_year","order_by"=>"meta_value");
// Same for other parameters
然后你可以简单地做
$sorting = $parameters[$sortby]["sort_by"];
$orderby = $parameters[$sortby]["order_by"];
此后的风格也不是很干净,肯定会产生通知
$sortby = $_GET['sort'] or $sortby = 'price';
更好的方法是
$sortby = isset($_GET['sort']) ? $_GET['sort'] : 'price';