A-AA+then

การเรียงลำดับ Array ด้วย key $array[key] = value

<?php
function name_sort($array, $type='asc') {
  $result=array();
  foreach($array as $var => $val){
    $set=false;
    foreach($result as $var2 => $val2){
      if ($set==false) {
        if ($var>$var2 && $type=='desc' || $var<$var2 && $type=='asc') {
          $temp=array();
          foreach($result as $var3 => $val3){
            if ($var3==$var2) $set=true;
            if ($set) {
              $temp[$var3]=$val3;
              unset($result[$var3]);
            }
          }
          $result[$var]=$val;
          foreach($temp as $var3 => $val3) {
            $result[$var3]=$val3;
          }
        }
      }
    }
    if (!$set) $result[$var]=$val;
  }
  return $result;
}
?>

ตัวอย่าง

<?
  $array[one]=1;
  $array[two]=2;
  $array[three]=3;
  $array[four]=4;

  $new_array=name_sort($array);
 
  print_r($new_array);//Array ( [four] => 4 [one] => 1 [three] => 3 [two] => 2 )
?>

Relate

^