简体   繁体   中英

Whats the most elegant way to rearrange an associative array?

Suppose you have an associative array

$hash['Fruit'] = 'Apple';
$hash['Name'] = 'Jeff';
$hash['Car'] = 'Ford';

and you cannot change the order in which these variables are created. So Car is always added to the array after Name, etc. What's the prettiest way to add/move Car to the beginning of the associative array instead of the end (default)?

$hash = array('Car' => 'Ford') + $hash;

ksort() ?

But why would you care about the array's internal order?

array_reverse($hash, true);

This is not a very direct solution but one that is:

$value = end($hash);
$hash = array(key($hash) => $value) + $hash;

Another trick is -

$new_items = array('Car' => 'Ford');
$hash = array_merge($new_items, $hash);

You can re arrange the new array keys also. Suppose car first then another field (say Id) then array remain so....

$new_items = array('Car' => 'Ford','Id'=>'New Id');
$hash = array_merge($new_items, $hash);

The array will become like

$hash['Car'] = 'Ford';
$hash['Id'] = 'New Id';
$hash['Fruit'] = 'Apple';
$hash['Name'] = 'Jeff';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM