arrays - Possible to pass a closure to usort in PHP? -


i have array sorting function follows:

public function sortascending($accounts) {     function ascending($accounta, $accountb) {         if ($accounta['amountuntilnexttarget'] == $accountb['amountuntilnexttarget']) {             return 0;         }         return ($accounta['amountuntilnexttarget'] < $accountb['amountuntilnexttarget']) ? -1 : 1;     }     usort($accounts, $ascending);      return $accounts; } 

clearly not ideal hard-coding key search for. thought make generic passing key param outside function, out-of-scope in inner function. tried around using closure, have access param, instead of inner function follows:

public function sortascending($accounts, $key) {     $ascending = function($accounta, $accountb) {         if ($accountsa[$key] == $accountb[$key]) {             return 0;         }         return ($accounta[$key] < $accountb[$key]) ? -1 : 1;     }     usort($accounts, $ascending);      return $accounts; } 

however usort() accepts function name, doesn't work. can see (better?) way of achieving this?

closures may inherit variables parent scope. such variables must declared in function header. inheriting variables parent scope not same using global variables. global variables exist in global scope, same no matter function executing. parent scope of closure function in closure declared (not function called from).

  • please note defining closure , assigning variable normal assignment operation, need ; after closing } of closure.

after making these changes code (and should work fine):

public function sortascending($accounts, $key) {     $ascending = function($accounta, $accountb) use ($key) {         if ($accountsa[$key] == $accountb[$key]) {             return 0;         }         return ($accounta[$key] < $accountb[$key]) ? -1 : 1;     };     usort($accounts, $ascending);      return $accounts; } 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -