0

The code below works and results in a multidimensional array sorted from lowest to highest gas proportion value

usort($BMEnergyArray, function($a, $b) {
              return $a['gasproportion'] - $b['gasproportion'];
              });

However, I need to call this function by passing a variable as the sort parameter, as below, which fails to sort correctly

$energyproportion = "'gasproportion'";

usort($BMEnergyArray, function($a, $b) {
              return $a[$energyproportion] - $b[$energyproportion];
              });

How do I achieve the sort using the variable?

Each item in the array is structured as below:

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 )

1 Answer 1

3

You can give it access by the function() use() syntax...

$energyproportion = "gasproportion";

usort($BMEnergyArray, function($a, $b) use ($energyproportion) {
              return $a[$energyproportion] - $b[$energyproportion];
              });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.