Wednesday, January 18, 2012

PHP Sort array by key values based on another array

When you are working with array and data field sets, sorting array by key value is very usefull to reorder data set based on your requirement.

Here is a PHP function to Sort array by key values based on another array








PHP Sort array by key values based on another array

<?php

//@param $array array need to sort
//@param $orderArray based array consider as correct order;
//Dependancy No:
function sort_array_from_array($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key => $value) {
        if(array_key_exists($key,$array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

$student=array(
  "Reg No"=>"19203",
  "Name"=>"John",
  "Age"=>"24",
  "Dor"=>"10-10-2010"
  );

// Target Order of the Key Values
$reorder_student=array(
   "Name"=>"",
   "Dor"=>"",
   "Reg No"=>"",
   "Age"=>""
   );
        
$output=sort_array_from_array($student,$reorder_student);

echo "<pre>";
print_r($output);


/* OUTPUT


Array
(
    [Name] => John
    [Dor] => 10-10-2010
    [Reg No] => 19203
    [Age] => 24
)
*/ ?>

No comments:

Post a Comment