PHP-数组排序

@lianst  September 2, 2017

分别定义一个数值数组和一个关联数组.

$age=array("lili"=>"23","bob"=>"30","ben"=>"44");
$cars=array("volvo","bmw","toyota");

1.sort()-对数组进行升序排列

//对数组进行升序排列
sort($cars);
//格式化打印
print_r($cars,false);
//输出变量的内容、类型或者字符串的内容、类型、长度。常用来调试
var_dump($cars);

//结果
array (size=3)
  0 => string 'bmw' (length=3)
  1 => string 'toyota' (length=6)
  2 => string 'volvo' (length=5)

2.rsort()-对数组进行降序排列

//降序排列
rsort($cars);
var_dump($cars);


//结果
array (size=3)
  0 => string 'volvo' (length=5)
  1 => string 'toyota' (length=6)
  2 => string 'bmw' (length=3)

3.asort()-根据数组的值,对数组进行升序排列

asort($age);
var_dump($age);

echo "<hr/>";


//结果
array (size=3)
  'lili' => string '23' (length=2)
  'bob' => string '30' (length=2)
  'ben' => string '44' (length=2)

4.arsort()-根据数组的值,对数组进行降序排列

arsort($age);
var_dump($age);

echo "<hr/>";

//结果
array (size=3)
  'ben' => string '44' (length=2)
  'bob' => string '30' (length=2)
  'lili' => string '23' (length=2)

5.ksort()-根据数组的键,对数组进行升序排列

ksort($age);
var_dump($age);

//结果
array (size=3)
  'ben' => string '44' (length=2)
  'bob' => string '30' (length=2)
  'lili' => string '23' (length=2)

6.krsort()-根据数组的键,对数组进行降序排列

krsort($age);
var_dump($age);

//结果
array (size=3)
  'lili' => string '23' (length=2)
  'bob' => string '30' (length=2)
  'ben' => string '44' (length=2)

添加新评论