Hello! I am just starting to learn PHP and I am having trouble understanding how to work with arrays. Maybe one of you can help me figure it out. I have a task: I need to create an array that will contain a list of products (for example, the name and price of each product), and then display this list on the screen in the form of an understandable table. So far, I have written the following code: Код (Text): <?php $products = array( array("name" => "Product 1", "price" => 100), array("name" => "Product 2", "price" => 200), array("name" => "Product 3", "price" => 300) ); foreach ($products as $product) { echo $product["name"] . " - " . $product["price"] . " rub.<br>"; } ?> The code seems to work, but the output is a simple list. How can I make the information appear as an HTML table? I would be grateful for code examples or links to articles that explain such things in detail. Thank you!
PHP: <?php $products = array( array("name" => "Product 1", "price" => 100), array("name" => "Product 2", "price" => 200), array("name" => "Product 3", "price" => 300) ); echo '<table border=1 cellspacing=4 cellpadding=0> <tr> <th>name</th> <th>price</th> </tr>'; $template = " <tr>\n <td>%s</td>\n <td>%d</td>\n </tr>\n"; foreach ($products as $product) { printf($template, htmlspecialchars($product["name"]), $product["price"]); } echo '</table>'; ?>
Hello! PHP: <html> <head> <style> table, td{border-collapse:collapse} td{padding: 3 5 3 5} </style> <head> <body> <?php class viewArray{ private function tableRow($cols) { $row = ""; foreach($cols as $col) $row .= "<td>$col</td>"; return "<tr>$row</tr>"; } public function arrayToHtmlTable($arr){ $table = "<table border=1>"; $table .= $this->tableRow(array_keys($arr[0])); foreach($arr as $row) $table .= $this->tableRow($row); $table .= "</table>"; return $table; } } $obj = new viewArray(); $products = array( array("name" => "Product 1", "price" => 100), array("name" => "Product 2", "price" => 200), array("name" => "Product 3", "price" => 300) ); echo $obj -> arrayToHtmlTable($products); $products = array( array("name" => "Product 1", "price" => 100, "height" => 10, "length" => 10 ), array("name" => "Product 2", "price" => 200, "height" => 20, "length" => 20), array("name" => "Product 3", "price" => 300, "height" => 30, "length" => 30 ) ); echo $obj -> arrayToHtmlTable($products); Good luck!