【发布时间】:2011-02-25 11:34:58
【问题描述】:
我编写的代码基于this similar question,但是我无法将其转换为在一个类中工作并且不使用全局变量。
这就是我想要做的。
假设我有 2 个数组:
$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 开始没有花哨的花哨)。
谢谢。
【问题讨论】:
-
您需要兼容低于 5.3 的 PHP 版本吗?
-
@BoltClock - 不幸的是。 5.2.14。我也会将其添加到问题中,谢谢。