|
Posted by Pedro Graca on 01/13/06 18:17
Pedro Graca wrote:
> <?php
<snip content="old version">
Updated version
Changes:
+ isolated the code inside a function
+ a lot more things :)
<?php // pivot.php
function pivotize($linear_table, $row, $col, &$pivot_table, &$columns, $callback) {
foreach ($linear_table as $val) {
if (!in_array($val[$col], $columns)) $columns[] = $val[$col];
if (!isset($pivot_table[$val[$row]][$val[$col]])) {
$pivot_table[$val[$row]][$val[$col]] = '';
}
call_user_func_array($callback, array(&$pivot_table[$val[$row]][$val[$col]], $val));
}
sort($columns);
}
?>
Example usage:
<?php
$data = array(
array('name'=>'joe', 'bio', 'grade'=>'a'),
array('name'=>'jill', 'chem', 'grade'=>'b'),
array('name'=>'john', 'psych', 'grade'=>'b'),
array('name'=>'john', 'chem', 'grade'=>'a'),
array('name'=>'joe', 'bio', 'grade'=>'a'),
array('name'=>'jill', 'psych', 'grade'=>'a'),
);
header('Content-Type: text/plain');
require_once 'pivot.php';
$new_data = array();
$classes = array();
pivotize($data, 'name', 0, $new_data, $classes, create_function('$x,$y', '$x.=$y[\'grade\'];'));
echo "name\t";
echo implode("\t", $classes);
echo "\n";
foreach ($new_data as $k=>$v) {
echo $k, "\t";
foreach ($classes as $class) {
echo isset($v[$class])?$v[$class]:'-', "\t";
}
echo "\n";
}
?>
--
Mail to my "From:" address is readable by all at http://www.dodgeit.com/
== ** ## !! ------------------------------------------------ !! ## ** ==
TEXT-ONLY mail to the whole "Reply-To:" address ("My Name" <my@address>)
may bypass my spam filter. If it does, I may reply from another address!
[Back to original message]
|