dumpfi
11-06-2005, 04:40 PM
This function sorts a multidimensional (tabular) array by one or more columns.
<?php
/* usage
sortDataSet(data set, column1[, mixed arg [, mixed ... [, array ...]]])
*/
/* arguments
the first argument is the multidimensional array
subsequent arguments follow the argument order of array_multisort(),
except that you do not pass arrays to the function but keys (string!) of the columns
*/
/* note
read the documentation of array_multisort() for more information
*/
function sortDataSet(&$dataSet) {
$args = func_get_args();
$callString = 'array_multisort(';
$usedColumns = array();
for($i = 1, $count = count($args); $i < $count; ++$i) {
switch(gettype($args[$i])) {
case 'string':
$callString .= '$dataSet[\''.$args[$i].'\'], ';
array_push($usedColumns, $args[$i]);
break;
case 'integer':
$callString .= $args[$i].', ';
break;
default:
throw new Exception('expected string or integer, given '.gettype($args[$i]));
}
}
foreach($dataSet as $column => $array) {
if(in_array($column, $usedColumns)) continue;
$callString .= '$dataSet[\''.$column.'\'], ';
}
eval(substr($callString, 0, -2).');');
}
/* example usage */
$latestPost = array(
'title' => array(
'title0',
'title1',
'title2',
'title5',
'title3'
),
'name' => array(
'name0',
'name1',
'name2b',
'name2a',
'name3'
),
'date' => array(
'0',
'1',
'2b',
'2a',
'3'
)
);
sortDataSet($latestPost, 'name', SORT_DESC, SORT_STRING, 'title', SORT_DESC, SORT_STRING);
echo '<pre>';
print_r($latestPost);
echo '</pre>';
?>dumpfi
<?php
/* usage
sortDataSet(data set, column1[, mixed arg [, mixed ... [, array ...]]])
*/
/* arguments
the first argument is the multidimensional array
subsequent arguments follow the argument order of array_multisort(),
except that you do not pass arrays to the function but keys (string!) of the columns
*/
/* note
read the documentation of array_multisort() for more information
*/
function sortDataSet(&$dataSet) {
$args = func_get_args();
$callString = 'array_multisort(';
$usedColumns = array();
for($i = 1, $count = count($args); $i < $count; ++$i) {
switch(gettype($args[$i])) {
case 'string':
$callString .= '$dataSet[\''.$args[$i].'\'], ';
array_push($usedColumns, $args[$i]);
break;
case 'integer':
$callString .= $args[$i].', ';
break;
default:
throw new Exception('expected string or integer, given '.gettype($args[$i]));
}
}
foreach($dataSet as $column => $array) {
if(in_array($column, $usedColumns)) continue;
$callString .= '$dataSet[\''.$column.'\'], ';
}
eval(substr($callString, 0, -2).');');
}
/* example usage */
$latestPost = array(
'title' => array(
'title0',
'title1',
'title2',
'title5',
'title3'
),
'name' => array(
'name0',
'name1',
'name2b',
'name2a',
'name3'
),
'date' => array(
'0',
'1',
'2b',
'2a',
'3'
)
);
sortDataSet($latestPost, 'name', SORT_DESC, SORT_STRING, 'title', SORT_DESC, SORT_STRING);
echo '<pre>';
print_r($latestPost);
echo '</pre>';
?>dumpfi