Sorting challenge

Posted by Felix Geisendörfer, on Oct 25, 2007 - in PHP & CakePHP » Other

Quick challenge,

lets say you have an array like this:

php
  1. $products = array(
  2.    array('Product' => array('ordering' => 5))
  3.    , array('Product' => array('ordering' => 3))
  4.    , array('Product' => array('ordering' => 9))
  5.    , array('Product' => array('ordering' => 1))
  6. );

and you want to iterate through your products by Product.ordering ASC. Whats the fastest way to do this? I just came up with this nifty little attempt, but I'd love to see some other solutions. (Rules: Don't use anything eval()'ish, but anything you find in Cake 1.2 can be used).

php
  1. $order = array_flip(Set::extract($products, '{n}.Product.ordering'));
  2. ksort($order);
  3. while ($product = $products[array_shift($order)]) {
  4.    debug($product);
  5. }

-- Felix Geisendörfer aka the_undefined