Friday, July 29, 2011

Array Sorting

Hello All,

Array play an important role in programming & is used vastly.
The sorting of an array with its key values is now become so easy.

suppose we have an array like:

Array
(
[0] => Array
(
[Name] => abc
[Email] => 123@yahoo.com
[Percentage] => 0
)

[1] => Array
(
[Name] => efg
[Email] => 123@yahoo.com
[Percentage] => 52.17
)

[2] => Array
(
[Name] => xyz
[Email] => 123@yahoo.com
[Percentage] => 8.0
)

)


Now add a function in our php script, this function will return an array which is sorted by key, you provide to method as parameter.




function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();

if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}

switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}

foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}

return $new_array;
}



Now call method:



$myarray = arrayData;
$myval = array_sort($myarray, 'Percentage', SORT_DESC); // Sort by oldest first


Full Example: (Try it)

<?

array("Name" => "abc", "Email" => "123@yahoo.com", "Percentage" => "0"),
"1"=>array("Name" => "fgh", "Email" => "123as@yahoo.com", "Percentage" => "52.17"),
"2"=>array("Name" => "qwe", "Email" => "erre324@yahoo.com", "Percentage" => "13.8"),
"3"=>array("Name" => "xyz", "Email" => "fdhgj33@yahoo.com", "Percentage" => "8.0")
);

$myval = array_sort($arrayData, 'Percentage', SORT_DESC); // Sort by oldest first
print_r($myval);


   function array_sort($array, $on, $order=SORT_ASC)
   {
     $new_array = array();
     $sortable_array = array();

     if (count($array) > 0) {
      foreach ($array as $k => $v) {
          if (is_array($v)) {
            foreach ($v as $k2 => $v2) {
                     if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
            }
          } else {
          $sortable_array[$k] = $v;
       }
     }

    switch ($order) {
     case SORT_ASC:
       asort($sortable_array);
       break;
    case SORT_DESC:
      arsort($sortable_array);
      break;
     }

      foreach ($sortable_array as $k => $v) {
         $new_array[$k] = $array[$k];
      }
   }

    return $new_array;
  }



?>

;




Note The function array_sort($array, $on, $order=SORT_ASC); i found it somewhere on internet,i put it here just for education purpose.I hope someone gets help from my this post.

Regards
Saleha