Location: PHPKode > scripts > Associative Quick Sort > Associative Quick Sort.php
   1.
      // convert associative array to 2d array
   2.
      function arr_convert_2d($arr) {
   3.
      $tmp_arr = array();
   4.
      foreach ($arr as $k => $v) {
   5.
      $tmp_arr[] = array('index' => $k, 'value' => $v);
   6.
      }
   7.
       
   8.
      return $tmp_arr;
   9.
      }
  10.
       
  11.
      // convert 2d associative array to 1d array
  12.
      function arr_convert_1d($arr) {
  13.
      $tmp_arr = array();
  14.
      foreach ($arr as $v) {
  15.
      $tmp_arr[$v['index']] = $v['value'];
  16.
      }
  17.
       
  18.
      return $tmp_arr;
  19.
      }
  20.
       
  21.
      function assoc_quicksort($arr)
  22.
      {
  23.
      if (!count($arr)) return $arr;
  24.
       
  25.
      $pivot = $arr[0];
  26.
      $left = $right = array();
  27.
       
  28.
      for($i = 1; $i < count($arr); $i++) {
  29.
      if($arr[$i]['value'] <= $pivot['value']) {
  30.
      $left[] = $arr[$i];
  31.
      }
  32.
      else {
  33.
      $right[] = $arr[$i];
  34.
      }
  35.
      }
  36.
       
  37.
      return array_merge(assoc_quicksort($left), array($pivot), assoc_quicksort($right));
  38.
      }
  39.
       
  40.
      $qsort_assoc_arr = arr_convert_1d(assoc_quicksort(arr_convert_2d($changed_arr)));
Return current item: Associative Quick Sort