gpt4 book ai didi

php - 从MySQL水平加载数据到表

转载 作者:可可西里 更新时间:2023-10-31 23:00:58 26 4
gpt4 key购买 nike

我正在从 MySQL 数据库加载一些数据,它看起来像这样:

| Gray |  S  |
| Gray | M |
| Gray | L |
| Red | S |
| Red | M |
| Red | L |

我想像这样水平加载数据到我的表格,按颜色分组:

| Gray |  S  |  M  |  L  |  XL  |
| Red | S | M | L | XL |

这是我的代码:

<table>
<?php foreach($products as $product) {?>
<tr>
<td><?php echo $product['color'];?></td>
<td><?php echo $product['size'];?></td>
</tr>
<?php }
?>
</table>

问题:如何将每行按颜色分组的数据加载到我的表中?我可以在没有单独的 MySQL 查询的情况下执行此操作吗?

最佳答案

一点点手动迭代将是你的 friend ...

$DatabaseResult = [ ['Gray','S'],['Gray','M'],['Gray','L'],['Red','S'],['Red','M'],['Red','L'] ];

$Grouped = array_fill_keys( array_unique( array_column( $DatabaseResult, 0 ) ), array() );

foreach( $DatabaseResult as $row )
{
$Grouped[ $row[0] ][] = $row[1];
}

print_r( $Grouped );

//Array
//(
// [Gray] => Array
// (
// [0] => S
// [1] => M
// [2] => L
// )
//
// [Red] => Array
// (
// [0] => S
// [1] => M
// [2] => L
// )
//)

然后您将创建两个循环,外部是您的“颜色”行,内部是您的“尺寸”列

<table border="1">
<?php foreach( $Grouped as $colour => $sizes ) {?>
<tr>
<td><?php echo $colour;?></td>
</td>
<?php foreach($sizes as $size) {?>
<td><?php echo $size;?></td>
<?php } ?>
</tr>
<?php } ?>
</table>

此外,如果您需要打印可用性尺码表,您可以这样做...

$Products = [
['color'=>'Gray','size'=>'S','quantity'=>2],
['color'=>'Gray','size'=>'M','quantity'=>4],
['color'=>'Gray','size'=>'L','quantity'=>7],
['color'=>'Red','size'=>'S','quantity'=>8],
['color'=>'Red','size'=>'M','quantity'=>6],
['color'=>'Red','size'=>'XXL','quantity'=>1],
];

// Helper function to locate products from the array
function SearchProductArray( $products, $color, $size )
{
foreach( $products as $product )
{
if( $product[ 'color' ] == $color and $product[ 'size' ] == $size )
{
return $product;
}
}
return false;
}

// Locate all the unique Values
$Colours = array_unique( array_column( $Products, 'color' ) );
$Sizes = ['SS','S','M','L','XL','XXL'];

?>

<table border="1">
<tr>
<td>Colour</td>
<?php foreach( $Sizes as $Size ) {?>
<td><?php echo $Size;?></td>
<?php } ?>
</tr>
<?php foreach( $Colours as $Colour ) {?>
<tr>
<td><?php echo $Colour;?></td>
<?php foreach( $Sizes as $Size ) { $Product = SearchProductArray( $Products, $Colour, $Size ); ?>
<td><?php echo ( $Product ) ? $Product['quantity'] : '&nbsp'; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>

关于php - 从MySQL水平加载数据到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50111459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com