Home > Backend Development > PHP Tutorial > 请教一个PHP排序的问题

请教一个PHP排序的问题

WBOY
Release: 2016-06-06 20:43:56
Original
774 people have browsed it

我要对数组进行数值排序,代码如下:

<code>$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
asort($a, SORT_NUMERIC);
var_dump($a);
</code>
Copy after login
Copy after login

打印结果如下:

<code>array(5) {
  'd' =>
  int(10)
  'a' =>
  int(10)
  'c' =>
  int(10)
  'z' =>
  int(10)
  'b' =>
  int(11)
}
</code>
Copy after login
Copy after login

问题:

  • 我需要对数值进行排序(已实现)
  • 若数值相同,则数组键的顺序位置不改变,请问如何做到

举例:
上面的数组

<code>$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
</code>
Copy after login
Copy after login

根据上面排序后,键的顺序依次为

d => 10, a => 10, c => 10, z => 10, b => 11

我希望能实现的顺序为为

a => 10, z => 10, c => 10, d => 10, b => 11

回复内容:

我要对数组进行数值排序,代码如下:

<code>$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
asort($a, SORT_NUMERIC);
var_dump($a);
</code>
Copy after login
Copy after login

打印结果如下:

<code>array(5) {
  'd' =>
  int(10)
  'a' =>
  int(10)
  'c' =>
  int(10)
  'z' =>
  int(10)
  'b' =>
  int(11)
}
</code>
Copy after login
Copy after login

问题:

  • 我需要对数值进行排序(已实现)
  • 若数值相同,则数组键的顺序位置不改变,请问如何做到

举例:
上面的数组

<code>$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
</code>
Copy after login
Copy after login

根据上面排序后,键的顺序依次为

d => 10, a => 10, c => 10, z => 10, b => 11

我希望能实现的顺序为为

a => 10, z => 10, c => 10, d => 10, b => 11

http://3v4l.org/fsQkS

<code>function hasort($arr) {
    $a = $b = array();
    foreach($arr as $v => $k) $a[$k][] = $v;
    ksort($a);
    foreach($a as $v => $i) 
        foreach($i as $k) $b[$k] = $v;
    return $b;
}
$a = array('a' => 10, 'z' => 10, 'c' => 10, 'b' => 11, 'd' => 10);
$a = hasort($a);
print_r($a);
/**
Array
(
    [a] => 10
    [z] => 10
    [c] => 10
    [d] => 10
    [b] => 11
)
**/
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template