开发者

How would i figure out the price difference efficiently with PHP?

I have this page and if you scroll to the second "Customize" in the middle of the page and you click you will see my print_r() for the products and the thing i am trying to do is figure out the difference in price between the selected and the other two products....all three products are in the array and if you look just below that you will see the radio buttons that i need....here is my php which looks awful...any suggestions

$current_price = $product[$selected_product]['product_price'];

$standard_price = $product["standard"]['product_price'] - $current_price;
$business_price = $pr开发者_开发技巧oduct["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;
}


As a starter, and with seeing the repeated code, I'd break your comparison out in to a function. Re-use code instead of copy-paste:

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);
}

Then it's a matter of:

$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


$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);
    }
}


It's pretty clear what's going on – I wouldn't say it's awful, and suspect that any tidying will actually make things harder to see what's happening.

If this had 500 different versions I'd fix it!

You could make an array with the 3 prices in, then do a foreach to produce the outcomes, but I probably wouldn't bother – it's not slow, and it's easy to understand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜