[英]Multidimensional array to table or split multidimensional arrays
可悲的是,我再次有一个小问题:-(
我现在有一个来自数据库的多维数组,我想将其写到表中,其中groupe
值应该是列标题,而所有具有相同groupe
值的记录都应该在列的行中。
数组按组排序。
在这里我的测试数组原始数组在子数组中有8个值,但我认为它将显示问题:
Array (
[0] => Array
( [0] => id [1] => name1 [2] => mail1 [3] => groupe1)
[1] => Array
( [0] => id2 [1] => name3 [2] => mail3 [3] => groupe1)
[2] => Array
( [0] => id3 [1] => name2 [2] => mail2 [3] => groupe2)
)
该表如下所示:
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td>Groupe 1</td>
<td>Groupe 2</td>
</tr>
<tr>
<td>name1</td>
<td>name2</td>
</tr>
<tr>
<td>name3</td>
</tr>
</table>
我认为该解决方案将是在剥离下来groupes
到一个维阵列通过头删除重复和循环。
然后由阵列分裂groupes
通过行和环...
但是我尝试过的所有事情都无法通过对新数组进行建模而失败...也许您知道一种更简单的方法:)
非常感谢你 !
看来您遇到了一个常见问题,您希望将数据显示为列而不是行。 解决方案是使用一个中间数组,在其中按组存储数据。
因此,循环遍历行,获取组,如果组不存在于数组中,则创建数组。 顺便说一句,您要计算组中的最大行数。 更简单的方法是循环访问组数组,并使用count和>。 如果组没有该索引的数据(使用isset()),则使用FOR循环达到最大值(使用isset()),显示并为空字符串,否则显示名称(或所需的数据)。
您可以使用2-3个循环来完成...:D
奖励:您可以通过在SQL查询中使用ORDER BY group_id来优化此算法,然后直接在第一个循环中获得最大长度。
得到它了 :-)
我认为此解决方案可能不是最佳解决方案,但它可以工作,并且可以用于类似情况。
我做了什么:
仅从数据数组中获取分组值并使其唯一。
将数据数组拆分为单独的分组数组
使用行的帮助表来构建表。
这是一个示例代码:
<?php
//Make test array Data;
$data = array();
$data[0][0] = 'Name1';
$data[0][1] = 'GroupeA';
$data[1][0] = 'Name2';
$data[1][1] = 'GroupeA';
$data[2][0] = 'Name3';
$data[2][1] = 'GroupeB';
print_r ($data);
echo ('</br>');
echo ('</br>');
//Get only all groupes from the data array and make it unique so every groupe is shown only once
//For the header and for counting.
$groups1 = array();
$groups2 = array();
$x = 0;
foreach($data as $value) {
$groups1[$x] = $value['1'];
$x ++;
}
$groups2 = array_unique($groups1); //Make unique so every groupe is shown only once in the array
$groups = array_values($groups2); // Renumber the Array Keys ( 0 to ?)
//Split the data array to seperate groupe arrays and give them auto names.
//So every Groupe has its own array called grpdata0 to grpdata?
$x = 0;
$x2 = 1;
$gr = count($groups);
while($gr>0) {
foreach($data as $value) {
if ($value[1] == $groups[$x]) {
${'grpdata' . $x}[$x2] = $value;
$x2++;
}
}
$gr--;
$x++;
}
// Renumber the array keys from the grpdata arrays ( 0 to ?)
$gr2 = count($groups)-1;
while($gr2>=0) {
${'grpdata' . $gr2} = array_values(${'grpdata' . $gr2});
$gr2--;
}
//Make the table
?>
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<?php //Make the header depending on the groups
foreach($groups as $value) {
echo ('<td><center>' . $value . '</center></td>');
}?>
</tr>
<tr>
<?php // Make the columns (by groupe) and add the rows (with a helping table)
$x = 0;
foreach($groups as $value) {
echo ('<td valign="top">');
foreach(${'grpdata' . $x} as $value) { ?>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td align="center"><?php echo $value[0]; ?></td>
</tr>
</table>
<?php
}
echo ('</td>');
$x++;
} ?>
</tr>
</table>
谢谢 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.