note 61334 deleted from function.array-multisort by cmb

From: Date: Sun, 29 Sep 2019 07:41:25 +0000
Subject: note 61334 deleted from function.array-multisort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212411@lists.php.net to get a copy of this message
Note Submitter: mail at theopensource dot com ---- I wanted to share with you a function that I created to make the array_multisort process much easier for myself... There was some interesting things that I encountered and I will post that in the comments. I created this function so that all I have to do is tell it what column I want to sort through in a one level deep multidimensional array. You can Try this code in your browser to view the results ex/ <?php //Here is an array example $test[0]['name'] = "David"; $test[0]['age'] = 28; $test[1]['name'] = "Dennis"; $test[1]['age'] = 23; $test[2]['name'] = "Joseph"; $test[2]['age'] = 42; //Here is the Function function sortmddata($array, $by, $order, $type){ //$array: the array you want to sort //$by: the associative array name that is one level deep ////example: name //$order: ASC or DESC //$type: num or str $sortby = "sort$by"; //This sets up what you are sorting by $firstval = current($array); //Pulls over the first array $vals = array_keys($firstval); //Grabs the associate Arrays foreach ($vals as $init){ $keyname = "sort$init"; $$keyname = array(); } //This was strange because I had problems adding //Multiple arrays into a variable variable //I got it to work by initializing the variable variables as arrays //Before I went any further foreach ($array as $key => $row) { foreach ($vals as $names){ $keyname = "sort$names"; $test = array(); $test[$key] = $row[$names]; $$keyname = array_merge($$keyname,$test); } } //This will create dynamic mini arrays so that I can perform //the array multisort with no problem //Notice the temp array... I had to do that because I //cannot assign additional array elements to a //varaiable variable if ($order == "DESC"){ if ($type == "num"){ array_multisort($$sortby,SORT_DESC, SORT_NUMERIC,$array); } else { array_multisort($$sortby,SORT_DESC, SORT_STRING,$array); } } else { if ($type == "num"){ array_multisort($$sortby,SORT_ASC, SORT_NUMERIC,$array); } else { array_multisort($$sortby,SORT_ASC, SORT_STRING,$array); } } //This just goed through and asks the additional arguments //What they are doing and are doing variations of //the multisort return $array; } //Now to test it $test = sortmddata($test,'age','ASC','num'); print_r ($test); //This will return //Array ( //[0] => Array ([name] => Dennis [age] => 23 ) //[1] => Array ( [name] => David [age] => 28 ) //[2] => Array ( [name] => Joseph [age] => 42 ) //) ?> There you go... please let me know what you think if you like.

« previous php.notes (#212411) next »