note 109398 added to function.ksort

From: Date: Fri, 13 Jul 2012 18:12:00 +0000
Subject: note 109398 added to function.ksort
Groups: php.notes 
Request: Send a blank email to php-notes+get-189127@lists.php.net to get a copy of this message
I wrote this function to sort the keys of an array using an array of keynames, in order. <?php /** * function array_reorder_keys * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order * @param array &$array - the array to reorder * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered */ function array_reorder_keys(&$array, $keynames){ if(empty($array) || !is_array($array) || empty($keynames)) return; if(!is_array($keynames)) $keynames = explode(',',$keynames); if(!empty($keynames)) $keynames = array_reverse($keynames); foreach($keynames as $n){ if(array_key_exists($n, $array)){ $newarray = array($n=>$array[$n]); //copy the node before unsetting unset($array[$n]); //remove the node $array = $newarray + array_filter($array); //combine copy with filtered array } } } $seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval'); array_reorder_keys($seed_array, 'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' ); ?> ---- Server IP: 64.71.164.2 Probable Submitter: 98.177.154.189 ---- Manual Page -- http://www.php.net/manual/en/function.ksort.php Edit -- https://master.php.net/note/edit/109398 Del: integrated -- https://master.php.net/note/delete/109398/integrated Del: useless -- https://master.php.net/note/delete/109398/useless Del: bad code -- https://master.php.net/note/delete/109398/bad+code Del: spam -- https://master.php.net/note/delete/109398/spam Del: non-english -- https://master.php.net/note/delete/109398/non-english Del: in docs -- https://master.php.net/note/delete/109398/in+docs Del: other reasons-- https://master.php.net/note/delete/109398 Reject -- https://master.php.net/note/reject/109398 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#189127) next »