The code that I have written is based on this similar question, however I'm having trouble working out convert it to work within a class and without the globals use.
Here's what I'm wanting to do.
Suppose I have 2 arrays:
$headings = array(
'id' => 'ID',
'name' => 'Name',
);
$rows = array(
array(
'id' => 1,
'name' => 'Jo Blogs',
),
array(
'name' => 'John Smith',
'id' => 2,
'other' => 'Potentially other data'
),
);
I would like to sort $rows
into the order specified in $headings
with any undefined keys appearing at the end. For example, after sorting $rows
would look like:
$rows = array(
array(
'id' => 1,
'name' => 'Jo Blogs',
),
array(
'id' => 2,
'name' => 'John Smith',
'other' => 'Potentially other data'
),
);
The code which works outside of a class is:
$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;
}
}
And outputs:
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)
Which is correct. So again, how do I get rid of the use of the global. I know that array_walk($rows, array($this, "sort_it"));
will use $this->sort_it()
. Unfortunately this has to work in PHP 5.2.14 (so no fancy fancy from 5.3).
Thanks.