我有一个复杂的多维数组;结构是这样的:
[
[
'countries' => [
['country_code' => 'US', 'growth' => 3.57],
['country_code' => 'CA', 'growth' => 4.77],
['country_code' => 'TT', 'growth' => 0],
],
'group_name' => 'North America',
],
[
'countries' => [
['country_code' => 'BR', 'growth' => 2.19],
['country_code' => 'PE', 'growth' => 1.78],
['country_code' => 'UY', 'growth' => 8.83],
['country_code' => 'MX', 'growth' => 3.83],
],
'group_name' => 'South America',
],
]
我想对每个国家/地区条目内的子数组进行排序(也许使用
array_multisort
),以便它们根据growth
(最高的第一个)进行排序
这样排序后的数组将是:
[
[
'countries' => [
['country_code' => 'CA', 'growth' => 4.77],
['country_code' => 'US', 'growth' => 3.57],
['country_code' => 'TT', 'growth' => 0],
],
'group_name' => 'North America',
],
[
'countries' => [
['country_code' => 'UY', 'growth' => 8.83],
['country_code' => 'MX', 'growth' => 3.83],
['country_code' => 'BR', 'growth' => 2.19],
['country_code' => 'PE', 'growth' => 1.78],
],
'group_name' => 'South America',
],
]
最坏的情况,你创建自己的排序函数并使用 usort。
它实际上是为这类事情而设计的。
在您的情况下,您将传递
$arr[$i]['countries']
并让比较函数基于 $arr['growth']
进行排序。
我已经使用以下排序功能多年了:
/**
* sorting array of associative arrays - multiple row sorting using a closure
* see also: the-art-of-web.com/php/sortarray/
* @param array $data input-array
* @param string|array $fields array-keys
* @license Public Domain
* @return array
*/
function sortArray( $data, $field )
{
$field = (array) $field;
uasort( $data, function($a, $b) use($field) {
$retval = 0;
foreach( $field as $fieldname )
{
if( $retval == 0 ) $retval = strnatcmp( $a[$fieldname], $b[$fieldname] );
}
return $retval;
} );
return $data;
}
// example call, sort by 'growth' first and by 'country_code' afterwards
// this would be equal to a MySQL 'ORDER BY `growth` ASC, `country_code` ASC'
foreach( $countryArray as &$item )
{
$item['countries'] = sortArray( $item['countries'], array( 'growth', 'country_code' ) );
}
通过
foreach()
循环,使用数组解构语法通过引用修改国家/地区数据。在循环体中,调用 usort()
并按降序增长对子数组行进行排序。
代码:(演示)
foreach ($array as ['countries' => &$countries]) {
usort($countries, fn($a, $b) => $b['growth'] <=> $a['growth']);
}
var_export($array);
可以使用
array_map()
对相同的技术进行功能样式设置,以生成数据的新变异副本。
代码:(演示)
var_export(
array_map(
function ($set) {
usort($set['countries'], fn($a, $b) => $b['growth'] <=> $a['growth']);
return $set;
},
$array
)
);