Home > Backend Development > PHP Tutorial > 数据排序取最大值

数据排序取最大值

WBOY
Release: 2016-06-23 13:29:17
Original
1104 people have browsed it

Array(    0 => Array    (        'id' => 1,            'level' => 6,            'layer' => 1        ),    '1' => Array    (        'id' => 15055,        [level] => 5,        [layer] => 2    ),    '2' => Array    (        'id' => 15056,        'level' => 5,        'layer' => 3    ),    '3' => Array    (        'id' => 15057,        'level' => 4,        'layer' => 4     ),    '4' => Array    (        'id' => 15058,        'level' => 4,        'layer' => 5    ))
Copy after login

如果level 相等就取layer较大的那个数组
最后得到的结果是这样的:
Array
(
0 => Array
(
'id' => 1,
'level' => 6,
'layer' => 1
),



'1' => Array
(
'id' => 15056,
'level' => 5,
'layer' => 3
),



'2' => Array
(
'id' => 15058,
'level' => 4,
'layer' => 5
)

)


回复讨论(解决方案)

有什么问题?冒泡一下不就完了么。。。。

可以使用 usort http://php.net/manual/zh/function.usort.php 函数。

$a = Array(    0 => Array    (        'id' => 1,            'level' => 6,            'layer' => 1        ),     '1' => Array    (        'id' => 15055,        'level' => 5,        'layer' => 2    ),     '2' => Array    (        'id' => 15056,        'level' => 5,        'layer' => 3    ),     '3' => Array    (        'id' => 15057,        'level' => 4,        'layer' => 4     ),     '4' => Array    (        'id' => 15058,        'level' => 4,        'layer' => 5    ) );$r = array();foreach($a as $v) {  if(! isset($r[$v['level']])) $r[$v['level']] = $v;  if($r[$v['level']]['layer'] < $v['layer']) $r[$v['level']] = $v;}$r = array_values($r);var_export($r);
Copy after login
array (  0 =>   array (    'id' => 1,    'level' => 6,    'layer' => 1,  ),  1 =>   array (    'id' => 15056,    'level' => 5,    'layer' => 3,  ),  2 =>   array (    'id' => 15058,    'level' => 4,    'layer' => 5,  ),)
Copy after login

楼主的数组从5个元素变成了3个,这用排序能实现吗?
贴出代码瞧瞧!

有什么问题?冒泡一下不就完了么。。。。



可以使用 usort http://php.net/manual/zh/function.usort.php 函数。

楼主的数组从5个元素变成了3个,这用排序能实现吗?
贴出代码瞧瞧!


有什么问题?冒泡一下不就完了么。。。。



可以使用 usort http://php.net/manual/zh/function.usort.php 函数。


哈哈,看错了,我以为他要排序。
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