PHP Multiple Dimension array and Object with and without a Defined Class
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>PHP array test</title>
</head>
<body>
<h1>Multi-dimensional array</h1>
<?php
// http://www.w3schools.com/php/php_arrays_multi.asp
// http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays
$arrayCars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo '<table cellpadding="5" cellspacing="1" border="1">
<tr>
<th>Row</th>
<th>Name</th>
<th>Stock</th>
<th>Sold</th>
</tr>';
for ($row = 0; $row < count($arrayCars); $row++) {
echo "<tr><th>$row</th>";
for ($col = 0; $col < 3; $col++) {
echo "<td>" . $arrayCars[$row][$col] . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
<h1>Object w/o Defined Class</h1>
<?php
// http://www.webmaster-source.com/2009/08/20/php-stdclass-storing-data-object-instead-array/
// http://stackoverflow.com/questions/931407/what-is-stdclass-in-php
$stateAL = new stdClass;
$stateAL->name = 'Alabama';
$stateAL->flower = 'Camellia';
$stateAL->animal = 'Black Bear';
$stateAL->bird = 'Yellowhammer Woodpecker';
$stateAK = new stdClass;
$stateAK->name = 'Alaska';
$stateAK->flower = 'Forget-me-not';
$stateAK->animal = 'Moose';
$stateAK->bird = 'Willow Ptarmigan';
$stateAZ = new stdClass;
$stateAZ->name = 'Arizona';
$stateAZ->flower = 'Cactus Blossom';
$stateAZ->animal = 'Ringtail';
$stateAZ->bird = 'Cactus Wren';
$initObjStates = array($stateAL, $stateAK, $stateAZ);
echo '<table cellpadding="5" cellspacing="1" border="1">
<tr>
<th>Name</th>
<th>Flower</th>
<th>Animal</th>
<th>Bird</th>
</tr>';
foreach ($initObjStates as $state) {
echo '<tr>
<th>' . $state->name . '</th>
<td>' . $state->flower . '</td>
<td>' . $state->animal . '</td>
<td>' . $state->bird . '</td>
</tr>';
}
echo '</table>';
?>
<h1>Object w/Defined Class</h1>
<?php
// http://stackoverflow.com/questions/8612190/array-of-php-objects
class objStates
{
public $name;
public $flower;
public $animal;
public $bird;
}
$stateAL = new objStates();
$stateAL->name = 'Alabama';
$stateAL->flower = 'Camellia';
$stateAL->animal = 'Black Bear';
$stateAL->bird = 'Yellowhammer Woodpecker';
$stateAK = new objStates();
$stateAK->name = 'Alaska';
$stateAK->flower = 'Forget-me-not';
$stateAK->animal = 'Moose';
$stateAK->bird = 'Willow Ptarmigan';
$stateAZ = new objStates();
$stateAZ->name = 'Arizona';
$stateAZ->flower = 'Cactus Blossom';
$stateAZ->animal = 'Ringtail';
$stateAZ->bird = 'Cactus Wren';
$initObjStates = array($stateAL, $stateAK, $stateAZ);
echo '<table cellpadding="5" cellspacing="1" border="1">
<tr>
<th>Name</th>
<th>Flower</th>
<th>Animal</th>
<th>Bird</th>
</tr>';
foreach ($initObjStates as $state) {
echo '<tr>
<th>' . $state->name . '</th>
<td>' . $state->flower . '</td>
<td>' . $state->animal . '</td>
<td>' . $state->bird . '</td>
</tr>';
}
echo '</table>';
?>
</body>
</html>