Reputation: 407
I have a multidimensional array that im trying to get to out put a table like this , using the foreach method. I get the array to string conversion error, and I've been playing around with it for a bit now can anyone point me in the right direction?
<?php
$DogToys = array();
$DogToys[0] = array("collar","14.99","red", "smooth");
$DogToys[1] = array("Bow","4.99","pink", "silky");
$DogToys[2] = array("booties","24.99","green", "smooth");
$DogToys[3] = array("Tail Bow","5.99","pink", "Satin");
$DogToys[4] = array("ear clip","7.99","green", "plastic");
?>
<h5>Accessories For Sale -- Well Worth a Second Look!</h5>
<?php
echo "<table>";
foreach($DogToys as $accesories) {
echo "<tr>";
echo "<td>".$accesories."</td>";
echo "</tr>";
echo "<br >";
}
echo "</table>";
?>
Upvotes: 1
Views: 3134
Reputation:
You just need another loop as it's multi-dimensional:
<?php
$DogToys = array();
$DogToys[0] = array("collar","14.99","red", "smooth");
$DogToys[1] = array("Bow","4.99","pink", "silky");
$DogToys[2] = array("booties","24.99","green", "smooth");
$DogToys[3] = array("Tail Bow","5.99","pink", "Satin");
$DogToys[4] = array("ear clip","7.99","green", "plastic");
?>
<h5>Accessories For Sale -- Well Worth a Second Look!</h5>
<?php
echo "<table border='1'>"; //to match your imaage
foreach ($DogToys as $each){
echo "<tr>";
foreach ($each as $accesories){
echo "<td>" . $accesories . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Upvotes: 2
Reputation: 2400
Your $DogToys
array is a multidimensional array. When you use:
foreach($DogToys as $accessories) {
...
}
each $accessories
is also an array -- an array within your array.
Try this instead:
<?php
$DogToys = array();
$DogToys[0] = array("collar","14.99","red", "smooth");
$DogToys[1] = array("Bow","4.99","pink", "silky");
$DogToys[2] = array("booties","24.99","green", "smooth");
$DogToys[3] = array("Tail Bow","5.99","pink", "Satin");
$DogToys[4] = array("ear clip","7.99","green", "plastic");
?>
<h5>Accessories For Sale -- Well Worth a Second Look!</h5>
<?php
echo "<table>";
foreach($DogToys as $accesories) {
echo "<tr>";
echo "<td>".$accesories[0]."</td>
<td>".$accesories[1]."</td>
<td>".$accesories[2]."</td>
<td>".$accesories[3]."</td>";
echo "</tr>";
echo "<br >";
}
echo "</table>";
?>
Alternately, you could apply what you did to the outer array ($DogToys
) to each inner array ($accessories
):
<h5>Accessories For Sale -- Well Worth a Second Look!</h5>
<?php
echo "<table>";
foreach($DogToys as $accesories) {
echo "<tr>";
foreach ($accessories as $item) {
echo "<td>".$item."</td>";
}
echo "</tr>";
echo "<br >";
}
echo "</table>";
?>
Upvotes: 2