Problem:
You have a table containing data with multiple dimensions, and you want to create a cross-tabulated table (pivot table) dynamically without knowing the number of dimensions upfront.
Solution:
The number of columns for a pivot query must be defined at query preparation time. To achieve dynamic cross-tabulation, you have two options that involve writing application code:
Option 1: Query Distinct Values and Construct Dynamic SQL
Example:
foreach ($pdo->query("SELECT DISTINCT `way` FROM `MyTable`") as $row) {
$way = (int) $row["way"];
$way_array[] = "MAX(IF(`way`=$way, `time`)) AS way_$way";
}
$pivotsql = "SELECT stop, " . join(", ", $way_array) .
"FROM `MyTable` GROUP BY `stop`";
Option 2: Query and Post-Process Data Row by Row
Example:
$stoparray = array();
foreach ($pdo->query("SELECT * FROM `MyTable`") as $row) {
$stopkey = $row["stop"];
if (!array_key_exists($stopkey, $stoparray)) {
$stoparray[$stopkey] = array("stop"=>$stopkey);
}
$waykey = "way_" . $row["way"];
$stoparray[$stopkey][$waykey] = $row["time"];
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3