|
Posted by Pedro Graca on 01/12/06 19:17
["Followup-To:" header set to comp.lang.php.]
manny wrote:
> I wish I knew what this was called, and I could have made a more sensible
> subject. For that matter, I knew what it was called, I could have googled it!
Not sure if it's useful but, if I'm not mistaken,
Excel calls it a "pivot table".
> Anyway, let's I have a table with name, class, grade.
>
> joe bio a
> jill chem b
> john psych b
> john chem a
> jill pysch a
>
> and I want to display the results as
>
> name bio psych chem
> joe a - -
> jill - a b
> john - b a
>
> Is there a way to do this with sql?
I don't know. Maybe someone on mailing.database.mysql will answer you.
.... you may want to try posting to comp.databases.mysql or some
newsgroup about sql in general.
Followups set to comp.lang.php because my answer is strictly php.
> How about sql with php?
Easy :)
With no need for sql at all.
Hope I'm not doing your homework ...
<?php
$data = array(
array('joe', 'bio', 'a'),
array('jill', 'chem', 'b'),
array('john', 'psych', 'b'),
array('john', 'chem', 'a'),
array('jill', 'psych', 'a'),
); /* could come from a database */
/* restructure data and get classes */
$new_data = array();
$classes = array();
foreach ($data as $val) {
if (!in_array($val[1], $classes)) $classes[] = $val[1];
if (isset($new_data[$val[0]][$val[1]])) {
$new_data[$val[0]][$val[1]] .= $val[2];
} else {
$new_data[$val[0]][$val[1]] = $val[2];
}
}
sort($classes);
header('Content-Type: text/plain'); /* I'm lazy */
/* print header */
echo "name\t";
echo implode("\t", $classes);
echo "\n";
/* print data rows */
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]
|