什么是重新排列关联数组的最优雅方式?

时间:2021-08-15 00:20:54

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)?

并且您无法更改创建这些变量的顺序。因此Car总是在Name之后添加到数组中。将Car添加/移动到关联数组的开头而不是结尾(默认)的最漂亮的方法是什么?

4 个解决方案

#1


8  

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

#2


2  

ksort() ?

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

但是你为什么要关心阵列的内部秩序呢?

#3


1  

array_reverse($hash, true);

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

这不是一个非常直接的解决方案,但它是:

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

#4


0  

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....

您也可以重新排列新的数组键。假设汽车首先是另一个领域(比如说Id),那么阵列仍然是......

$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';

#1


8  

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

#2


2  

ksort() ?

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

但是你为什么要关心阵列的内部秩序呢?

#3


1  

array_reverse($hash, true);

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

这不是一个非常直接的解决方案,但它是:

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

#4


0  

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....

您也可以重新排列新的数组键。假设汽车首先是另一个领域(比如说Id),那么阵列仍然是......

$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';