Tuesday, September 20, 2011

Object sort by Key value using PHP

/**
 * Function to swap two array with Values.
 * @param $&$data
 *   Array to be passed for swapping.
 * @param $key
 *   Filed name to be checked for
 * @return
 *   Swapped array.
 */
function objectSort(&$data, $key) {
  for ($i = count($data) - 1; $i >= 0; $i--) {
    $swapped = false;
    for ($j = 0; $j < $i; $j++) {
      if ($data[$j]->$key > $data[$j + 1]->$key){
        $tmp = $data[$j];
        $data[$j] = $data[$j + 1];
        $data[$j + 1] = $tmp;
        $swapped = true;
      }
    }
    if (!$swapped) return;
  }
}

No comments: