下面的代码起作用,并导致从最低到最高气体比例值排序的多维数组
usort($BMEnergyArray, function($a, $b) {
return $a['gasproportion'] - $b['gasproportion'];
});
但是,我需要通过传递一个变量作为排序参数来调用此函数,如下所示,该变量无法正确排序
$energyproportion = "'gasproportion'";
usort($BMEnergyArray, function($a, $b) {
return $a[$energyproportion] - $b[$energyproportion];
});
如何使用变量实现排序?
数组中的每个项目的结构如下:
Array ( [0] => Array ( [time] => 2018-11-01 01:40:00 [gas] => 13159 [coal] => 503 [nuclear] => 5822 [wind] => 2499 [hydro] => 263 [biomass] => 3024 [solar] => 0 [gasproportion] => 52 [coalproportion] => 2 [nuclearproportion] => 23 [windproportion] => 10 [hydroproportion] => 1 [biomassproportion] => 12 [solarproportion] => 0 )
答案 0 :(得分:3)
您可以通过function() use()
语法为其授予访问权限...
$energyproportion = "gasproportion";
usort($BMEnergyArray, function($a, $b) use ($energyproportion) {
return $a[$energyproportion] - $b[$energyproportion];
});