为什么sort与多维数组一起使用? [英] Why does asort work with multidimensional arrays?

查看:117
本文介绍了为什么sort与多维数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个非常基本的问题.我无意间发现 asort() 似乎可用于多维数组:

Apologies if this is a really basic question. I've inadvertently discovered that asort() appears to work with multidimensional arrays:

示例PHP

$animals = array(
  1 => array('name' => 'Zebra'),
  2 => array('name' => 'Fox'),
  3 => array('name' => 'Rabbit'),
  4 => array('name' => 'Dog'),
  5 => array('name' => 'Cat')
);

asort($animals);
var_dump($animals);

输出

array
  5 => 
    array
      'name' => string 'Cat' (length=3)
  4 => 
    array
      'name' => string 'Dog' (length=3)
  2 => 
    array
      'name' => string 'Fox' (length=3)
  3 => 
    array
      'name' => string 'Rabbit' (length=6)
  1 => 
    array
      'name' => string 'Zebra' (length=5)

我想知道为什么会这样吗?

我认为 asort() 仅对平面数组进行了排序,并对多维数组进行了排序定义自定义排序功能所需的数组.在说明上述行为的文档中找不到任何内容.

I thought asort() only sorted flat arrays, and to sort multidimensional arrays you needed to define a custom sort function. I can't find anything in the documentation that explains the above behaviour.

推荐答案

按字母顺序将数组的值与其值进行比较,因此第一个元素为"cat"的数组小于第一个元素为"cat"的数组斑马".这只是正常的一维排序,碰巧会将数组彼此比较.

Arrays are compared in the lexicographical order by their values, so an array where the first element is "cat" is less than an array where the first element is "zebra". This is just a normal single dimension sort that happens to compare arrays to each other.

例如:

php > var_dump(array('a')< array('b'));
bool(true)
php > var_dump(array('a')> array('b'));
bool(false)

这篇关于为什么sort与多维数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆