1 回答
TA贡献1811条经验 获得超5个赞
您可以循环数组并使用usort()
<?php
$data['test1'][0] = array('total' => 67, 'edition' => 2, 'pkg_version' => "2.5.0" );
$data['test1'][1] = array('total' => 67, 'edition' => 2, 'pkg_version' => "0.1.0" );
$data['test1'][2] = array('total' => 67, 'edition' => 2, 'pkg_version' => "0.3.0" );
$data['test2'][0] = array('total' => 86, 'edition' => 1, 'pkg_version' => "1.5.0");
$data['test2'][1] = array('total' => 85, 'edition' => 6, 'pkg_version' => "0.53.0");
$data['test2'][2] = array('total' => 98, 'edition' => 2, 'pkg_version' => "0.3");
$data['test2'][3] = array('total' => 98, 'edition' => 2, 'pkg_version' => "0.2");
$data['test3'][0] = array('total' => 60, 'edition' => 6, 'pkg_version' => "0.3");
$data['test3'][1] = array('total' => 60, 'edition' => 7, 'pkg_version' => "0.1.1");
$data['test3'][2] = array('total' => 60, 'edition' => 7, 'pkg_version' => "0.25");
// use a reference to the sub array
// |
// |
// v
foreach ($data as &$row)
{
usort($row, function($a, $b)
{
// make a desc sort by comparing $b against $a instead of $a against $b
return strcmp($b['pkg_version'], $a['pkg_version']);
});
}
var_dump($data);
这输出:
array(3) {
["test1"]=>
array(3) {
[0]=>
array(3) {
["total"]=>
int(67)
["edition"]=>
int(2)
["pkg_version"]=>
string(5) "2.5.0"
}
[1]=>
array(3) {
["total"]=>
int(67)
["edition"]=>
int(2)
["pkg_version"]=>
string(5) "0.3.0"
}
[2]=>
array(3) {
["total"]=>
int(67)
["edition"]=>
int(2)
["pkg_version"]=>
string(5) "0.1.0"
}
}
["test2"]=>
array(4) {
[0]=>
array(3) {
["total"]=>
int(86)
["edition"]=>
int(1)
["pkg_version"]=>
string(5) "1.5.0"
}
[1]=>
array(3) {
["total"]=>
int(85)
["edition"]=>
int(6)
["pkg_version"]=>
string(6) "0.53.0"
}
[2]=>
array(3) {
["total"]=>
int(98)
["edition"]=>
int(2)
["pkg_version"]=>
string(3) "0.3"
}
[3]=>
array(3) {
["total"]=>
int(98)
["edition"]=>
int(2)
["pkg_version"]=>
string(3) "0.2"
}
}
["test3"]=>
&array(3) {
[0]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(6)
["pkg_version"]=>
string(3) "0.3"
}
[1]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(7)
["pkg_version"]=>
string(4) "0.25"
}
[2]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(7)
["pkg_version"]=>
string(5) "0.1.1"
}
}
}
请注意,在最后一个数组中, version0.3高于 version 0.25。由于这是您预期输出中的顺序,因此我将其保留为原样,但如果不是,您可以使用 , 代替strcmp(),version_compare()这将为 提供以下输出$data['test3']:
["test3"]=>
&array(3) {
[0]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(7)
["pkg_version"]=>
string(4) "0.25"
}
[1]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(6)
["pkg_version"]=>
string(3) "0.3"
}
[2]=>
array(3) {
["total"]=>
int(60)
["edition"]=>
int(7)
["pkg_version"]=>
string(5) "0.1.1"
}
}
}
- 1 回答
- 0 关注
- 121 浏览
添加回答
举报