Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.
$custo
Without magic...
$array=array(28=>c,4=>b,5=>a);
$seq=array(5,4,28);
SortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);
function sortByKeyList($array,$seq){
$ret=array();
if(empty($array) || empty($seq)) return false;
foreach($seq as $key){$ret[$key]=$dataset[$key];}
return $ret;
}
A bit late, but I couldn't find the way I implemented it, this version needs closure, php>=5.3, but could be altered not to:
$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';
$order = array('name', 'dob', 'address');
$keys= array_flip($order);
uksort($customer, function($a, $b)use($keys){
return $keys[$a] - $keys[$b];
});
print_r($customer);
Of course 'dontSortMe' needs to be sorted out, and may appear first in the example
I used the Darkwaltz4's solution but used array_fill_keys
instead of array_flip
, to fill with NULL
if a key is not set in $array
.
$properOrderedArray = array_replace(array_fill_keys($keys, null), $array);