我写的代码是基于这个类似的问题,但是我在尝试将其转换为类内部运行时遇到了困难,而且不能使用全局变量。
这就是我想要做的事情。
假设我有两个数组:
$headings = array(
'id' => 'ID',
'name' => 'Name',
);
$rows = array(
array(
'id' => 1,
'name' => 'Jo Blogs',
),
array(
'name' => 'John Smith',
'id' => 2,
'other' => 'Potentially other data'
),
);
我希望将$rows
按照$headings
中指定的顺序进行排序,未定义的键会出现在最后。例如,排序后$rows
的样子会是这样的:
$rows = array(
array(
'id' => 1,
'name' => 'Jo Blogs',
),
array(
'id' => 2,
'name' => 'John Smith',
'other' => 'Potentially other data'
),
);
在类外工作的代码是:
$headings = array(
'id' => 'ID',
'name' => 'Name',
);
$rows = array(
array(
'id' => 1,
'name' => 'Jo Blogs',
),
array(
'name' => 'John Smith',
'id' => 2,
'other' => 'Potentially other data'
),
);
var_dump($rows);
array_walk($rows, "sort_it");
var_dump($rows);
function sort_it(&$value, $key) {
uksort($value, "cmp");
}
function cmp($a, $b) {
global $headings;
if (!isset($headings[$a]) || !isset($headings[$b]) || $headings[$a]>$headings[$b]){
return 1;
}else{
return -1;
}
}
并输出:
array
0 =>
array
'id' => int 1
'name' => string 'Jo Blogs' (length=8)
1 =>
array
'name' => string 'John Smith' (length=10)
'id' => int 2
'other' => string 'Potentially other data' (length=22)
array
0 =>
array
'id' => int 1
'name' => string 'Jo Blogs' (length=8)
1 =>
array
'id' => int 2
'name' => string 'John Smith' (length=10)
'other' => string 'Potentially other data' (length=22)
哪个是正确的。所以,我如何消除使用全局变量。我知道array_walk($rows, array($this, "sort_it"));
将使用$this->sort_it()
。不幸的是,这必须在PHP 5.2.14中工作(因此不能使用5.3中的花哨特性)。
谢谢。