-4

我试图在表格中以特定方式显示数组数据,所以我需要像这样格式化我的数组:

               Leafy Life - Aspley - All Green
Callistemon1 -     33     -        - 
Callistemon2 -            -        - 3.59
Acronychia   -            -  22.5  - 

我已经尝试了很多次,但是我的知识有限,如果有人能指出我正确的方向,或者即使你有时间调整我的代码,我将不胜感激。<?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 "&nbsp;". $i;
            echo "</td>";
        
        $i++;
        echo "<td>";
        echo $v;
        echo "</td>";
        
    }
    
    echo "</tr>";
}

echo "</tbody>";
echo "</table>";


?>
4

1 回答 1

1

我们可以像这样改变数组的结构 -

$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";

现在在显示时 - 首先添加所有列“标题”数组中的所有内容。

然后对于每一行 - 使用“firstCloumnEntries”数组使用循环索引获取第一个值。编写一个内部循环来打印相应的行值。在打印该值之前,请使用isset().

索引“0”被故意消除,因为我们在第 0 列第 0 行中没有任何值。header 数组或 firstCloumnEntries 数组中的索引将帮助我们了解其中元素的 ID,例如 1 是“Leafy Life”的 ID,2 是“Aspley”的 ID,依此类推.. 使用它我们可以添加更多的标题新 ID 和更多具有更多 ID 的 firstCloumnEntries。这将有助于添加动态内容并使循环变得容易。

于 2013-05-18T11:19:55.817 回答