0

I have an array that comes in this way since it's generated this way, and it's a heck of a task to change the way it's generated. This is part of it, there loads more.

$name['Age'] = '25';
$name['Location'] = 'Seattle';
$name['Last'] = 'Gates';
$name['First'] = 'Bill';

print_r($name);

How can I change it's order to something like below once it's generated?

$name['First'] = 'Bill';
$name['Last'] = 'Gates';
$name['Age'] = '25';
$name['Location'] = 'Seattle';

print_r($name);
4

1 回答 1

4

是的,有一个函数可以让您根据自己的标准通过键重新排序关联数组。它被称为uksort

$key_order = array_flip(['First', 'Last', 'Age', 'Location']);
uksort($name, function($key1, $key2) {
  return $key_order[$key1] - $key_order[$key2];
});

print_r($name);

演示


说了这么多,我不禁想知道您是否需要一些不同的东西:仅更改数组的输出顺序。例如:

$output_order = ['First', 'Last', 'Age', 'Location'];
foreach ($output_order as $key) {
  echo $key, ' => ', $name[$key], PHP_EOL;
}
于 2013-10-27T14:07:20.440 回答