Reputation: 631
having some issues with getting the output from an array. I've looked around and can't seem to find out why my array isn't assigning an index to each portion of an array. I've looked around and even tried adding a counter variable to the piece of the array but that doesn't seem to create an index. I'm pretty new to PHP so any help that anyone can give me would be appreciated.
foreach($dbh->query('SELECT n_productID, t_productName, t_categoryName FROM v_prodcatintersect') as $row) {
$prodID=$row["n_productID"];
$prodName=$row["t_productName"];
$prodCategor=$row["t_categoryName"];
$products=array(
array(
"prodID" => $prodID,
"prodName" => $prodName,
"prodCategor" => $prodCategor
),
print_r($products);
}
for($i = 0, $size = sizeof($products); $i < $size; ++$i){
echo "The product ID is ".$products[$i]["prodID"];
echo " The product name is ".$products[$i]["prodName"];
echo " Product Category ".$products[$i]["prodCategor"];
}
Right now the output from the array (from the print_r) is "Array ( [0] => Array ( [prodID] => 1 [prodName] => iPhone 4 [prodCategor] => Smartphones ) ) Array ( [0] => Array ( [prodID] => 2 [prodName] => Droid 3 [prodCategor] => Smartphones ) )". And the echo's only print the second item out of two since they both have the same index. Appreciate any help with creating an index here. Thanks.
Upvotes: 0
Views: 1574
Reputation: 5843
Try doing this - [] will increment key index every time you add a sub-array into your multidimensional array.
$products[] = array(
"prodID" => $prodID,
"prodName" => $prodName,
"prodCategor" => $prodCategor
)
Upvotes: 1
Reputation: 5701
To add a new item to an existing array, you can use the following syntax:
$products[] = array(
'prodID' => $prodID,
'prodName' => $prodName,
'prodCategor' => $prodCategor);
This will append a new entry into the end of an existing array. So, $products
at the end of the foreach loop will give you the following instead of just overwriting the contents of $products
. This allows you to increment through $products in your second for loop correctly.
array(
[0] => array(
[prodID] => 1
[prodName] => iPhone
[prodCategor] => Smartphones)
[1] => array(
[prodID] => 2
[prodName] => Droid
[prodCategor] => Smartphones))
Upvotes: 2