2016-12-27 80 views
0

請點我在哪裏我錯了我的形式,以及如何獲得訪問$ _ POST數據通過它的關鍵如何通過PHP數組中的鍵訪問值?

這裏是我的表單輸入:

<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; ?>"> 

捕獲數據:

$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>"; 
} 

陣列:

> [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 這樣的工作,但不能findout IA爲什麼不能獲得通過的關鍵

foreach ($products_in_cart as $product) { 
    foreach ($product as $p) { 
     echo $p . "<br>"; 

     // This not works: 
     // echo $p['product_name'] . "<br>"; 
    } 
} 
+0

你能迴應類似'$ products_in_cart [1] ['price_for_item']'嗎? – Michel

回答

1

訪問而不是使用for loop的你應該使用foreach loop這樣的:

foreach($products_in_cart as $arr) { 
    echo "<pre>"; 
    print_r($arr); 
    echo "</pre>"; 

    // Access inner keys 
    echo $arr['product_name'] . "<br>"; 
} 

查看更多有關foreach()docs

+0

不適用於我的情況=( – DeN

1

您是否嘗試過做類似:

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>"; 
    } 
+0

不,這不適用於我的情況 – DeN

1

如果您的帖子末尾輸出的數組是正確的,那麼您有一個包含關聯數組的數字索引數組。所以你需要循環通過數字數組,然後通過鍵訪問特定的關聯數組。

<?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); 
    } 
} 
?> 
相關問題