Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中关联数组元素的排序_Php_Associative Array - Fatal编程技术网

PHP中关联数组元素的排序

PHP中关联数组元素的排序,php,associative-array,Php,Associative Array,我得到了一个关联数组,如下所示: $data['england']='pound' $data['america']='dollar' $data['europe']='euro' $data['denmark']='krone' $data['japan']='yen' 我想对这个数组进行排序,然后我想让“europe”成为数组中的第一个元素。为了对数组进行排序,我在php中使用了ksort(),现在我如何获得“europe”数组对象,使其成为第一个元素并向下移动所有剩余元素?一个解决方案是

我得到了一个关联数组,如下所示:

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

我想对这个数组进行排序,然后我想让“europe”成为数组中的第一个元素。为了对数组进行排序,我在php中使用了ksort(),现在我如何获得“europe”数组对象,使其成为第一个元素并向下移动所有剩余元素?

一个解决方案是首先从数组中删除europe,然后执行ksort。对数组进行排序后,可以使用或将europe添加为数组中的第一个元素

使用合并的示例:

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


使用
+
运算符不会像合并运算符那样重新索引数组

您可以使用回调进行排序:

$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;
});

我建议使用更好的数据结构如果您已经在手册中找到了
ksort
,是什么阻止了您研究其他
*排序
功能?另外,您的排序逻辑是什么?只是把欧洲放在第一位?其他元素呢?我的排序逻辑是所有元素都应该按键排序,除了“euro”应该在顶部!!不,它没有!!它使用ksort()按字母顺序排序。我不知道的是,为什么我问这个问题是想知道,一个人如何在不知道键的情况下访问关联数组中的元素。e、 g在普通数组中,u可以使用数组[0]获取第一个元素,数组[1]获取第二个元素,数组[2]获取第三个元素…当其关联数组为时,如何获取第一、第二和第三个etc元素$数组[0]不一定返回第一个元素。它返回带有数字键0的元素。偏移量/位置0处的元素可能是,但可能不是。如果要从该数组中获取欧洲,请使用$array['Europe']。请更新您的阵列知识,网址为