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
}
}
如何传递带有名称空间的数组参数,因为我发现的所有其他引用都没有名称空间,所以我迷失了。感谢任何建议。
我尝试过的:
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);
}
但这将返回 PHP 错误:PHP 致命错误:未捕获错误:不在对象上下文中时使用 $this
PHP 编辑器链接:
命名空间或类与这里的任何内容都没有什么关系。你只想要一个匿名回调:
$sortMe = array(...);
$sorted = array(...);
usort($sortMe , function ($a, $b) use ($sorted) {
return array_search($a, $sorted) - array_search($b, $sorted);
});