数组映射?
我有
$A= array("A1"=>array("x"=>1,"b"=>2,"d"=>3,"s"=>8),
"A2"=>array("a"=>4,"b"=>3,"c"=>2,"d"=>1)
);
输出(HTML):
| a | b | c | d | x | s
------------------------------
A1 | 0 | 2 | 0 | 3 | 1 | 8
A2 | 4 | 3 | 2 | 1 | 0 | 0
有人知道怎么做吗?
检索密钥
$keys = array_unique(array_merge (array_keys($A['A1']), array_keys($A['A2'])));
然后创建输出
echo " | ";
echo implode(' | ', $keys) . "n";
echo "n";
foreach ($A as $name => $oneA) {
echo "$name ";
foreach ($keys as $key) echo "| ". (isset($oneA[$key]) ? $oneA[$key] : 0);
echo "n";
}
或作为html表
<table>
<tr>
<td> </td>
<td><?php implode('</td><td>', $keys);</td>
</tr>
<?php foreach ($A as $name => $oneA) : ?>
<tr>
<td><?php echo $name; ?></td>
<?php foreach ($keys as $key): ?>
<td><?php echo isset($oneA[$key]) ? $oneA[$key] : 0; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
您可以在键之前对其进行排序并格式化输出。这只是缩写形式。
首先,收集内部数组中的所有密钥:
$keys = array_keys(
array_reduce($A, function ($a, $b) { return $a + $b; }, array()));
sort($keys);
打印标题,最后在行上迭代,对于每行,在键上迭代:
foreach ($A as $lineKey => $lineValue) {
//TODO: print $lineKey;
foreach ($keys as $k) {
//TODO: print $lineValue[$k]; or 0
}
}