我的数组如下:
YourView.Top
我想将此数组提取为表格形式:
Array
(
[0] => Array
(
[product_id] => 19
[attributes] => Array
(
[0] => Array
(
[label] => Hard Disk
[name] => harddisk
[value] => 500 GB
)
[1] => Array
(
[label] => RAM
[name] => ram
[value] => 16 GB
)
[2] => Array
(
[label] => Graphics
[name] => graphics
[value] => 2 GB
)
[3] => Array
(
[label] => Graphics Card
[name] => graphicscard
[value] => 2 GB
)
)
)
[1] => Array
(
[product_id] => 20
[attributes] => Array
(
[0] => Array
(
[label] => Hard Disk
[name] => harddisk
[value] => 1 TB
)
[1] => Array
(
[label] => RAM
[name] => ram
[value] => 8 GB
)
[2] => Array
(
[label] => Graphics
[name] => graphics
[value] => 1 GB
)
[3] => Array
(
[label] => Graphics Card
[name] => graphicscard
[value] => 1 GB
)
)
)
)
可能会出现另一个产品ID,因为它是动态的。我能够获得第一列,但如何获得其他列。我的代码是:
Product ID | 19 | 20
Hard Disk | 500 GB | 1 TB
RAM | 16 GB | 8 GB
Graphics | 2 GB | 1 GB
Graphics Card | 2 GB | 1 GB
答案 0 :(得分:1)
我总是对HTML和PHP的混合感到困惑。我更喜欢更清晰的外观。
我会分两步解决你的问题:
1:将数组转换为可以轻松呈现为表格的数组。
2:从该数组中渲染表格。
if (is_array($all)) {
// step 1: create table
foreach ($all as $one) {
$id = $one['product_id'];
$table['Product Id'][$id] = $id;
foreach ($one['attributes'] as $attribute) {
$label = $attribute['label'];
$value = $attribute['value'];
$table[$label][$id] = $value;
}
}
// step 2: render the table
echo '<table class="table">'.PHP_EOL;
foreach ($table as $label => $row) {
echo "<tr><td>$label</td>";
foreach ($table['Product Id'] as $id) {
echo '<td>'.(isset($row[$id]) ? $row[$id] : '-').'</td>';
}
echo '</tr>'.PHP_EOL;
}
echo '</table>'.PHP_EOL;
}
此例程可以处理缺少的属性。
此代码并不完美,但它为您提供了一个重点。挑战是进一步降低复杂性。我认为这是可能的。