开发者

How does asort work?

开发者 https://www.devze.com 2023-02-13 15:12 出处:网络
I was having a look over some of my old work and saw that the asort function would have worked perfectly for some of the uses I needed, although I attempted an extremely different and longwinded way.

I was having a look over some of my old work and saw that the asort function would have worked perfectly for some of the uses I needed, although I attempted an extremely different and longwinded way.

So my question is exactly, how does asort maintain association when sorting? I thought an a开发者_开发知识库rray can be sorted by key, or by value, is there a third sorting pivot?


The "third pivot" is the actual location in memory/array.
You will see it clearly when doing a foreach on the following two arrays, which are the same, but have different order:

$x1=array('mmm'=>'mmm','bbb'=>'bbb','ccc'=>'ccc');
$x2=array('ccc'=>'ccc','bbb'=>'bbb','mmm'=>'mmm');

foreach($x1 as $k=>$v) echo "{$k} {$v}";
foreach($x2 as $k=>$v) echo "{$k} {$v}";

doing the default asort on those two arrays will result in both cases in:

$x1=array('bbb'=>'bbb','ccc'=>'ccc','mmm'=>'mmm');
$x2=array('bbb'=>'bbb','ccc'=>'ccc','mmm'=>'mmm');


From the manual :

asort — Sort an array and maintain index association

So, for example :

  • Asort will just sort by value in ascending way keeping the index=>value association.
  • Arsort is the same but in desc way.

The manual is pretty clear on Array sorting function here.

Basic function only sort by key or values but there are options:

  • index->value association maintained or not
  • Use of a custom function for sorting or not
  • Asc or Desc
  • case sensitive or not
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号