我有这个page,如果你滚动到页面中间的第二个“自定义”,你点击你将看到我的print_r()产品和我想要做的事情是图在所选产品和其他两个产品之间的价格差异....所有三个产品都在数组中,如果你看下面你会看到我需要的单选按钮....这里是我的PHP看起来糟糕......任何建议
$current_price = $product[$selected_product]['product_price'];
$standard_price = $product["standard"]['product_price'] - $current_price;
$business_price = $product["business"]['product_price'] - $current_price;
$premium_price = $product["premium"]['product_price'] - $current_price;
if($standard_price == 0){
$standard_price = "included";
}
if($standard_price > 0){
$standard_price = "subtract " . $standard_price;
}else{
$standard_price = "add " . $standard_price;
}
if($business_price == 0){
$business_price = "included";
}
if($business_price > 0){
$business_price = "subtract " . $business_price;
}else{
$business_price = "add " . $business_price;
}
if($premium_price == 0){
$premium_price = "included";
}
if($premium_price > 0){
$premium_price = "subtract " . $premium_price;
}else{
$premium_price = "add " . $premium_price;
}
答案 0 :(得分:2)
作为首发,并且看到重复的代码,我会将你的比较分解为一个函数。重复使用代码而不是复制粘贴:
function price_delta($base,$compare){
if ($base == $compare)
return 'included';
$delta = $compare - $base;
return $delta > 0 ? sprintf("add $%01.2f", $delta) : sprintf("subtract $%01.2f", $delta * -1);
}
然后是一个问题:
$standard_price = price_delta($current_price, $product["standard"]['product_price']);
$business_price = price_delta($current_price, $product["business"]['product_price']);
$premium_price = price_delta($current_price, $product["premium"]['product_price']);
<强> DEMO 强>
答案 1 :(得分:1)
$alt_prices=array('standard','business','premium');
$current_price = $product[$selected_product]['product_price'];
foreach($alt_prices as $alt_price){
$$alt_price=$product[$alt_price]['product_price']-$current_price;
if($$alt_price==0){
$$alt_price='Included';
}else{
$$alt_price=($$alt_price>0)?'subtract '.abs($$alt_price):'add '.abs($$alt_price);
}
}
答案 2 :(得分:0)
很明显发生了什么 - 我不会说这很可怕,并怀疑任何整理都会让事情变得更加难以看清正在发生的事情。
如果这有500个不同的版本,我会解决它!
你可以制作一个包含3个价格的数组,然后做一个foreach来产生结果,但我可能不会打扰 - 它不慢,而且很容易理解。