PHP/HTML/HTML Table

Материал из Web эксперт
Версия от 07:05, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating an HTML table from array elements

 
<?
    $languages = array ("a" => "A",
                        "b" => "B",
                        "q" => "Q");
    
    print "<table>";
    reset ($languages);
    $hd1 = key ($languages);
    $hd2 = $languages[$hd1];
    print "<tr><th>$hd1</th><th>$hd2</th></tr>";
    next($languages);
    
    while ( list ($ctry,$lang) = each ($languages)) :
         print "<tr><td>$ctry</td><td>$lang</td></tr>";
    endwhile;
    
    print "</table>";
?>



Output a HTML table

 
<html> 
<head> 
<title>Table Example</title> 
</head> 
<body> 
<table> 
<?php 
    $Cars = array ("Ford","Dodge","Chevy"); 
    $CarId = array ("K","J","F"); 
    for($x=0; $x < count($Cars); $x++){ 
        print "<tr><td>$CarId[$x]</td>"; 
        print "<td>$Cars[$x]</td></tr>\n"; 
    } 
?> 
</table> 
</body> 
</html>



Separate the city and state name in the array so we can total by state

 
<?
$population = array("New York"     => array("state" => "NY", "pop" => 8008278),
                    "San Antonio"  => array("state" => "TX", "pop" => 1144646),
                    "Detroit"      => array("state" => "MI", "pop" => 951270));
$state_totals = array();
$total_population = 0;
print "<table><tr><th>City</th><th>Population</th></tr>\n";
foreach ($population as $city => $info) {
    $total_population += $info["pop"];
    $state_totals[$info["state"]] += $info["pop"];
    print "<tr><td>$city, {$info["state"]}</td><td>{$info["pop"]}</td></tr>\n";
    
}
foreach ($state_totals as $state => $pop) {
    print "<tr><td>$state</td><td>$pop</td>\n";
}
print "<tr><td>Total</td><td>$total_population</td></tr>\n";
print "</table>\n";
?>



Use for each to loop through an array and create a table

 
$population = array("New York, NY" => 8008278,
                    "Los Angeles, CA" => 3694820,
                    "Chicago, IL" => 2896016);
$total_population = 0;
print "<table><tr><th>City</th><th>Population</th></tr>\n";
foreach ($population as $city => $people) {
    $total_population += $people;
    print "<tr><td>$city</td><td>$people</td></tr>\n";
    
}
print "<tr><td>Total</td><td>$total_population</td></tr>\n";
print "</table>\n";