Reputation: 669
Please point me where am i wrong with my form and how to get access to $_POST data by it's key
Here are my form inputs:
<input type="hidden" name="<?php echo $products_in_cart; ?>['product_name']" value="<?php echo $_SESSION['cart']['products'][$val['sku']]['product_name']; ?>">
<input type="hidden" name="<?php echo $products_in_cart; ?>['qty_in_cart']" value="<?php echo $_SESSION['cart']['products'][$val['sku']][$qty]; ?>">
<input type="hidden" name="<?php echo $products_in_cart; ?>['price_for_item']" value="<?php echo $val['price_item']; ?>">
<input type="hidden" name="<?php echo $products_in_cart; ?>['price_for_all_items_in_cart']" value="<?php echo $price_item_total; ?>">
Catching data:
$products_in_cart = $_POST['products_in_cart'];
for ($i=0; $i < count($products_in_cart); $i++) {
echo "<pre>";
print_r($products_in_cart[$i]);
echo "</pre>";
// !!! ISSUE: Can't access by this key
// echo $products_in_cart[$i]['product_name'] . "<br>";
}
Array:
> [products_in_cart] => Array
> (
> [0] => Array
> (
> ['product_name'] => Котёл на отработанном масле «EcoBoil-18/30»
> ['qty_in_cart'] => 1
> ['price_for_item'] => 35200
> ['price_for_all_items_in_cart'] => 35200
> )
>
> [1] => Array
> (
> ['product_name'] => Калорифер воздушный «HotAir-2/36»
> ['qty_in_cart'] => 2
> ['price_for_item'] => 48000
> ['price_for_all_items_in_cart'] => 96000
> )
>
> )
UPD This way works, but can't findout why i a can't gain access by key
foreach ($products_in_cart as $product) {
foreach ($product as $p) {
echo $p . "<br>";
// This not works:
// echo $p['product_name'] . "<br>";
}
}
Upvotes: 0
Views: 82
Reputation: 2215
If your array output at the end of your post is correct, then you have a numerically indexed array that contains associative arrays. So you need to loop thru the numeric array, then access that particular associative array by the key.
<?php
// print just the product_name
for($i=0;$i<count($products_in_cart);$i++){
print($products_in_cart[$i]['product_name']);
}
// print everything about the products_in_cart
for($i=0;$i<count($products_in_cart);$i++){
foreach($products_in_cart[$i] as $key=>$value){
print($key." : ".$value);
}
}
?>
Upvotes: 1
Reputation: 153
Have you tried doing something like:
foreach($products_in_cart as $product) {
echo "<pre>";
echo $product['product_name']. "<br>";
echo $product['qty_in_cart']. "<br>";
echo $product['price_for_item']. "<br>";
//and so on...
echo "</pre>";
}
Upvotes: 1
Reputation: 13693
Instead of using for loop
you should use foreach loop
like this:
foreach($products_in_cart as $arr) {
echo "<pre>";
print_r($arr);
echo "</pre>";
// Access inner keys
echo $arr['product_name'] . "<br>";
}
See more about foreach()
from the docs
Upvotes: 1