PHP, sort, sort_flags

烈酒焚心 提交于 2021-02-16 13:14:36

问题


I am studying sort_flags at this page on PHP Manual.

And I don't understand what difference each of these flags represents.

There are only 6 flags, can someone please help me to understand the difference between them. Maybe with some examples. I would be very thankful.


回答1:


Array used for testing:

$toSort = array(2, 1, "img1", "img2", "img10", 1.5, "3.14", "2.72");

Note that 3.14 & 2.72 are strings.

Using SORT_REGULAR flag (compare items normally):

Array
(
    [0] => 2.72
    [1] => 3.14
    [2] => img1
    [3] => img10
    [4] => img2
    [5] => 1
    [6] => 1.5
    [7] => 2
)

Using SORT_NUMERIC flag (compare items numerically, so 3.14 is sorted as number not a string):

Array
(
    [0] => img10
    [1] => img1
    [2] => img2
    [3] => 1
    [4] => 1.5
    [5] => 2
    [6] => 2.72
    [7] => 3.14
)

Using SORT_STRING flag (SORT_LOCALE_STRING works similary, but depends on current locale, all values are treated as strings):

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 2.72
    [4] => 3.14
    [5] => img1
    [6] => img10
    [7] => img2
)

Using SORT_NATURAL flag (note order of img* strings, it is natural):

Array
(
    [0] => 1
    [1] => 1.5
    [2] => 2
    [3] => 2.72
    [4] => 3.14
    [5] => img1
    [6] => img2
    [7] => img10
)

SORT_FLAG_CASE can be combined with SORT_STRING or SORT_NATURAL to do case-insensitive sort e.g.:

// works like SORT_NATURAL but is case-insensitive
sort($toSort, SORT_NATURAL | SORT_FLAG_CASE);


来源:https://stackoverflow.com/questions/11168523/php-sort-sort-flags

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!