简体   繁体   中英

Sorting associative array elements in PHP

i have got an associative array as follows:

$data['england']='pound'
$data['america']='dollar'
$data['europe']='euro'
$data['denmark']='krone'
$data['japan']='yen'

I want to sort this array and after that i want 'europe' to be the first element in the array. To sort the array, i am using ksort() in php, now how can i get hold of the 'europe' array object so that i can make it the first element and shift all the remaining elements down?

One solution would be to first remove europe from the array and then do the ksort. When the array is sorted you can use the array_unshift() or array_merge() to add europe as the first element in the array.

An example using merge:

<?php
$data['england']='pound';
$data['america']='dollar';
$data['europe']='euro';
$data['denmark']='krone';
$data['japan']='yen';

unset($data['europe']);
ksort($data);
$data = array('europe' => 'euro') + $data;

print_r($data);
?>

Usage of the + operator will not reindex the array as the merge-operator would.

You could use a callback for sorting:

$data = array (
  'england' => 'pound',
  'america' => 'dollar',
  'europe' => 'euro',
  'denmark' => 'krone',
  'japan' => 'yen'
);

uksort($data, function($a, $b) {
  if($a == 'europe') return -1;
  if($b == 'europe') return 1;
  return $a > $b;
});

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