如何在PHP数组中通过键访问值?

时间:2016-12-27 15:45:07

标签: php arrays

请指出我的表单错误,以及如何通过密钥访问$ _POST数据

以下是我的表单输入:

<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 这种方式有效,但无法找出为什么我无法通过密钥访问

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

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

3 个答案:

答案 0 :(得分: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>";
}

docs

了解foreach()的更多信息

答案 1 :(得分: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>";
    }

答案 2 :(得分: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);
    }
}
?>