在php中对数字字符串数组进行排序 [英] sort numeric string array in php

查看:146
本文介绍了在php中对数字字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 php 数组,如:

I have a php array like :

myarr[1] = "1",
myarr[2] = "1.233",
myarr[3] = "0",
myarr[4] = "2.5"

值实际上是字符串,但我希望这个数组按数字排序,同时考虑浮点值和保持索引关联.

the values are actually strings but i want this array to be sorted numerically, also considering float values and maintaining index association.

请帮帮我.谢谢

推荐答案

你可以使用普通的sort 功能.它需要第二个参数来告诉您要如何对其进行排序.选择 SORT_NUMERIC.

You can use the normal sort function. It takes a second parameter to tell how you want to sort it. Choose SORT_NUMERIC.

示例:

  sort($myarr, SORT_NUMERIC); 
  print_r($myarr);

印刷品

Array
(
    [0] => 0
    [1] => 1
    [2] => 1.233
    [3] => 2.5
)

更新:要维护键值对,请使用 asort(采用相同的参数),示例输出:

Update: For maintaining key-value pairs, use asort (takes the same arguments), example output:

Array
(
    [3] => 0
    [1] => 1
    [2] => 1.233
    [4] => 2.5
)

这篇关于在php中对数字字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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