我写的代码基于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 2011-02-25 11:36:29
@BoltClock - 不幸的是。 5.2.14。我也将这个补充到这个问题上,谢谢。 – 2011-02-25 11:42:07