Example: php 2D array sorting code.
- // Description: sorting of two-dimensional arrays in PHP
- // Finishing: http://bbs.it-home.org
-
- /**
- * @ Package BugFree
- * @ Version $ Id: FunctionsMain. inc. php, v 1.32 11:38:37 wwccss Exp $
- *
- *
- * Sort an two-dimension array by some level two items use array_multisort () function.
- *
- * SysSortArray ($ Array, "Key1", "SORT_ASC", "SORT_RETULAR", "Key2 "......)
- * @ Author Chunsheng Wang
- * @ Param array $ ArrayData the array to sort.
- * @ Param string $ KeyName1 the first item to sort.
- * @ Param string $ SortOrder1 the order to sort by ("SORT_ASC" | "SORT_DESC ")
- * @ Param string $ SortType1 the sort type ("SORT_REGULAR" | "SORT_NUMERIC" | "SORT_STRING ")
- * @ Return array sorted array.
- */
- Function sysSortArray ($ ArrayData, $ KeyName1, $ SortOrder1 = "SORT_ASC", $ SortType1 = "SORT_REGULAR ")
- {
- If (! Is_array ($ ArrayData ))
- {
- Return $ ArrayData;
- }
-
- // Get args number.
- $ ArgCount = func_num_args ();
-
- // Get keys to sort by and put them to SortRule array.
- For ($ I = 1; $ I <$ ArgCount; $ I ++)
- {
- $ Arg = func_get_arg ($ I );
- If (! Eregi ("SORT", $ Arg ))
- {
- $ KeyNameList [] = $ Arg;
- $ SortRule [] = '$'. $ Arg;
- }
- Else
- {
- $ SortRule [] = $ Arg;
- }
- }
-
- // Get the values according to the keys and put them to array.
- Foreach ($ ArrayData AS $ Key => $ Info)
- {
- Foreach ($ KeyNameList AS $ KeyName)
- {
- $ {$ KeyName} [$ Key] = $ Info [$ KeyName];
- }
- }
-
- // Create the eval string and eval it.
- $ EvalString = 'Array _ multisort ('. join (",", $ SortRule).', $ ArrayData );';
- Eval ($ EvalString );
- Return $ ArrayData;
- }
-
-
- #################
- $ Arr = array (
- Array (
- 'Name' => 'learn ',
- 'Size' => '123 ',
- 'Type' => 'jpe ',
- 'Time' => '2017-11-13 ',
- 'Class' => 'DD ',
- ),
- Array (
- 'Name' => 'Kung Fu China ',
- 'Size' => '123 ',
- 'Type' => 'jpe ',
- 'Time' => '2017-11-13 ',
- 'Class' => 'JJ ',
- ),
- Array (
- 'Name' => 'programmatically ',
- 'Size' => '35 ',
- 'Type' => 'GIF ',
- 'Time' => '2017-11-13 ',
- 'Class' => 'DD ',
- ),
- Array (
- 'Name' => 'Kung Fu China ',
- 'Size' => '65 ',
- 'Type' => 'jpe ',
- 'Time' => '2017-02-13 ',
- 'Class' => 'yy ',
- ),
- Array (
- 'Name' => 'Kung Fu China ',
- 'Size' => '5 ',
- 'Type' => 'Icon ',
- 'Time' => '2017-12-13 ',
- 'Class' => 'rr ',
- ),
- );
-
- Print_r ($ arr );
-
- // Note: When sorting by number, 153 is smaller than 65.
- $ Temp = sysSortArray ($ arr, "name", "SORT_ASC", "type", "SORT_DESC", "size", "SORT_ASC", "SORT_STRING ");
-
- Print_r ($ temp );
- ?>
|