<?php
 
// Sort the items by quantity and return the matching one.
 
uasort($items, 'commerce_price_table_sort_by_qty');
  foreach (
$items as $item) {
    if (
$quantity <= $item['max_qty'] && $quantity >= $item['min_qty']) {
      return
$item;
    }
  }

 
// Handle the unlimited qty.
 
foreach ($items as $item) {
    if (
$item['max_qty'] == -1) {
      return
$item;
    }
  }

 
// We fallback to the higher one if no match was found.
 
return end($items);
?>

If the quantity is less than or equal to the maximum quantity and not greater than or equal to the lesser ... Then it automatically "-1"

Regards

Comments

facine’s picture

Status:Active» Needs review

I forgot to change the status!

Cybso’s picture

Status:Closed (duplicate)» Needs review

No, in this implementation the loop is necessary, because max_qty = -1 must not be at the end:

$items = array(
  0 => array('min_qty' => 10, 'max_qty' => 17, 'amount' => 30),
  1 => array('min_qty' => 18, 'max_qty' => -1, 'amount' => 20),
  2 => array('min_qty' => 0, 'max_qty' => 9, 'amount' => 40),
  3 => array('min_qty' => 30, 'max_qty' => 40, 'amount' => 10),
);

After uasort:

$items = array(
  2 => array('min_qty' => 0, 'max_qty' => 9, 'amount' => 40),
  0 => array('min_qty' => 10, 'max_qty' => 15, 'amount' => 30),
  1 => array('min_qty' => 18, 'max_qty' => -1, 'amount' => 20),
  3 => array('min_qty' => 30, 'max_qty' => 40, 'amount' => 10),
);

If $quantity = 17 (gap) or $quantity = 100, the loop would return item 1 (amount = 20), without the loop it would return item 3 (amount = 10).

Please have also a look at http://drupal.org/node/1897824, which tries to make the behavior of price table predictable on gapping intervals.

pcambra’s picture

Status:Needs review» Closed (duplicate)

Thanks for the insight Cybso, I'll mark this as dupe of the gapping one

Status:Needs review» Closed (duplicate)