Reputation: 117
I need to sort the data into different columns together based on a defined lists. (instead of echoing them separately). As shown in the example below, ten different columns from mysql table containing list of mixed letters.
<table>
<tr>
<th>A,K,L</th>
<th>X,O,Z</th>
</tr>
<?php
include ("dbconfig.php");
$sql = "SELECT Stat1, Stat2, Stat3, Stat4, Stat5, Stat6, Stat7, Stat8, Stat9, Stat10 FROM Stats";
$result = $conn->query($sql);
The expected output would be like this:
How can I achieve this? Thanks.
Upvotes: 0
Views: 49
Reputation: 6953
The following snipped should do what you want - if I understood correctly. See inline comments for explanations!
<?php
// defining your 2 categories
$cat[1] = ["A","K","L"];
$cat[2] = ["X","O","Z"];
// mocking input data (but only 4 columns and 4 rows...)
$input = [
["Stat1"=>"A", "Stat2"=>"K", "Stat3"=>"Y","Stat4"=>"N"],
["Stat1"=>"X", "Stat2"=>"B", "Stat3"=>"K","Stat4"=>"M"],
["Stat1"=>"A", "Stat2"=>"K", "Stat3"=>"L","Stat4"=>"O"]
];
foreach($input as $row) { // this will be your while($row = mysqli_fetch*) {
// we could put the following into a loop (if categories should be dynamic)
$columns[1] = array_filter($row, function($col) use ($cat) {
if(in_array($col, $cat[1])) { // if the value is in category 1, add it
return true;
}
});
$columns[2] = array_filter($row, function($col) use ($cat) {
if(in_array($col, $cat[2])) { // if the value is in category 2, add it
return true;
}
});
$output[] = $columns; // add the 2 columns to the output as new row
}
// the actual output of the categorized data:
$table = <<<EOT
<table border=1>
<tr>
<th>A,K,L</th>
<th>X,O,Z</th>
</tr>
EOT;
foreach($output as $row) {
$table.="<tr>";
foreach($row as $column) {
$table .="<td>";
$values = implode(",",$column);
$table .= $values;
$table .="</td>";
}
$table.="</tr>";
}
$table.="</table>";
echo $table;
// OUTPUT:
A,K,L X,O,Z
-------------
A,K
K X
A,K,L O
The docs for relevant functions used: array_reduce(), implode(), in_array()
Upvotes: 2