note 109397 deleted from function.array-unshift by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:20:00 +0000 |
| Subject: | note 109397 deleted from function.array-unshift by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189181@lists.php.net to get a copy of this message | ||
Note Submitter: thegrandoverseer
----
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
}
}
}?>