namespace App\Controllers\Redis;
class getArray{
public function sortArray(){
$sortMe = Array
(
'05' => 100,
'15' => 1,
'24' => 10,
'32' => 1000,
);
$sorted= Array
(
'0' => 1,
'1' => 10,
'2' => 100,
'3' => 1000,
);
function cmp($a, $b) {
//I need to get $sorted here
return array_search($a, $sorted) - array_search($b, $sorted);
}
usort($sortMe , 'App\Controllers\Redis\cmp');//pass the $sorted parameter
}
}
How can I pass the array parameter with namespace as all others reference I found are without namespace so I am lost. Appreciate any advice.
what I tried:
private $sorted = []; //declace a private var in the class
$this->sorted= Array
(
'0' => 1,
'1' => 10,
'2' => 100,
'3' => 1000,
);
function cmp($a, $b) {
$sorted = $this->sorted;
return array_search($a, $sorted) - array_search($b, $sorted);
}
but this will return PHP error : PHP Fatal error: Uncaught Error: Using $this when not in object context
PHP editor Link:
The expected result : https://3v4l.org/gbbua#v7.0.14
My current program : https://3v4l.org/1Kmoq#v7.0.14
CodePudding user response:
Namespaces or classes have very little to do with anything here. You just want an anonymous callback:
$sortMe = array(...);
$sorted = array(...);
usort($sortMe , function ($a, $b) use ($sorted) {
return array_search($a, $sorted) - array_search($b, $sorted);
});