Wednesday, January 7, 2015

Sort PHP associate array by element value




For example, I have PHP associate array parents as following:
           $parents = array();
            $parents[]=array("tp_journal_id"=> "1000", "tp_parent_journal_id"=> NULL, "Code_Id"=> "2",
            "Rank_id"=> "0", "Stakeholder_Id"=>$instructor, "Tp_Categories_Id"=> NULL,
            "Courses_Offered_Has_Stakeholder_Id"=> NULL, "Courses_Offered_Id"=> NULL, "StartTerm"=>"1161",
            "EndTerm"=> "1161", "Transaction"=> NULL, "CourseReleaseValue"=> "0" ,
            "StudyLeaveValue"=>"1", "JournalEntries"=> "", "Status"=>"Active", "code_id"=>"2",
            "CodeAbb"=>"T", "Code"=>"Teaching", "Category"=> NULL, "tp_categories_id"=> NULL,
        "InstructorOverload"=> NULL, "sort"=>"1161" );
   
           $parents[] =array("tp_journal_id"=> "1000", "tp_parent_journal_id"=> NULL, "Code_Id"=> "1",
            "Rank_id"=> "0", "Stakeholder_Id"=>$instructor, "Tp_Categories_Id"=> NULL,
            "Courses_Offered_Has_Stakeholder_Id"=> NULL, "Courses_Offered_Id"=> NULL,       "StartTerm"=>"1154",
            "EndTerm"=> "1154", "Transaction"=> NULL, "CourseReleaseValue"=> "0" ,
            "StudyLeaveValue"=>"0", "JournalEntries"=> "", "Status"=>"Active", "code_id"=>"1",
            "CodeAbb"=>"R", "Code"=>"Research", "Category"=> NULL, "tp_categories_id"=> NULL,
        "InstructorOverload"=> NULL, "sort"=>"1154" );       


I want to sort array based on element StartTerm, PHP function usort can be used:
            usort($parents, function($a, $b) {
                return $a['StartTerm'] - $b['StartTerm'];
            });      
  

No comments:

Post a Comment