我试图在表中以特定的方式显示数组数据,所以我需要像这样格式化我的数组:
Leafy Life - Aspley - All Green
Callistemon1 - 33 - -
Callistemon2 - - - 3.59
Acronychia - - 22.5 -
我已经尝试了很多次,但我的知识有限,如果有人能给我指出正确的方向,或者即使你有时间调整我的代码,那将是非常感激的。& lt; ?php
$options = array(
array("plant" => "Callistemon Kings Park Special 300 mm","nursery" => "A Leafy Life","price" => "33"),
array("plant" => "Callistemon Kings Park Special 300 mm","nursery" => "Alpine Nurseries Alstonville","price" => "23"),
array("plant" => "Callistemon Kings Park Special 140 mm","nursery" => "All Green Nursery","price" => "3.59"),
array("plant" => "Acronychia imperforata 300 mm","nursery" => "Aspley Nursery","price" => "22.5"),
array("plant" => "Acronychia imperforata 300 mm","nursery" => "All Green Nursery","price" => "23"),
array("plant" => "Metrosideros collina Little Dugald 140 mm","nursery" => "Accent Plants","price" => "5.25"),
);
$newOptions = array();
foreach ($options as $option) {
$plant = $option['plant'];
$nursery = $option['nursery'];
$price = $option['price'];
$newOptions[$plant][$nursery] = $price;
}
print_r($newOptions);
echo "<table cellpadding='0' cellspacing='0' border='2'>";
echo "<thead>";
echo "<th></th>";
foreach($newOptions as $key => $row)
{
foreach($row as $k => $v)
{
print_r($k);
echo "<th>";
echo $k;
echo "</th>";
}
}
echo "</thead>";
echo "<tbody>";
$i=0;
foreach($newOptions as $keys => $rows)
{
echo "<tr>";
echo "<td>";
echo $keys;
echo "</td>";
foreach($rows as $v)
{
echo "<td>";
echo " ". $i;
echo "</td>";
$i++;
echo "<td>";
echo $v;
echo "</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
我们可以像这样改变数组的结构-
$Headers = array();
$headers[1] = "Leafy Life";
$headers[2] = "Aspley";
$headers[3] = "All Green";
$firstCloumnEntries = array();
$firstCloumnEntries[1] = "Callistemon1";
$firstCloumnEntries[2] = "Callistemon2";
$firstCloumnEntries[3] = "Acronychia";
$values = array();
$values[1] = array(); // this will have all values for first row;
$values[1][1] = "33";
$values[2] = array(); // this will have all values for second row;
$values[2][3] = "3.59";
$values[1] = array(); // this will have all values for third row;
$values[3][2] = "22.5";
现在在显示时-首先添加所有列"header"数组中的所有内容。
然后,对于每一行,使用"firstCloumnEntries"数组使用循环索引获取第一个值。编写一个内部循环来打印相应的行值。在打印该值之前,请使用isset()
.
索引"0"被故意删除,因为我们在第0列第0行中没有任何值。头数组或firstCloumnEntries数组中的索引将帮助我们理解其中元素的ID,例如1是"绿叶生活"的ID, 2是"Aspley"的ID,等等。使用它,我们可以添加更多带有新id的头,以及更多带有更多id的firstCloumnEntries。这将有助于添加动态内容并使循环变得容易。