简体   繁体   English

引用嵌套数组中的变量

[英]Referencing variables in nested arrays

I'm trying to reference the "suggested" variable within this nested array as it gets spit out of a for loop. 我试图在此嵌套数组中引用“建议”变量,因为它会从for循环中吐出。 $_SESSION["products"]->suggested, did not work. $ _SESSION [“ products”]->建议,不起作用。 There are other questions like this on SO but the answers are hard to follow. 在SO上还有其他类似的问题,但是答案很难遵循。 The for loop is below. for循环如下。

array(1) {
  ["products"]=>
    array(1) {
    [0]=>
     array(9) {
     ["name"]=>
    string(20) "m10x1-5-001 IVB bolt"
    ["code"]=>
  string(11) "m10x1-5-001"
  ["qty"]=>
  string(1) "1"
  ["weight"]=>
  string(3) ".03"
  ["price"]=>
  string(5) "37.00"
  ["image"]=>
  string(80) "/images/ProductPhotosLR/m101-5-001/m10x1-5-001-S.jpg"
  ["description"]=>
  string(39) "This is a short description of my item."
  ["suggested"]=>
  string(18) "IVB-METRIC-INSTALL"
  ["suggestedtext"]=>
  string(80) "First time owners of ....."
  }
  }
}

The loop I'm trying to use: (every item in a cart session would have a suggested item attached potentially) for loop works fine, if statement is broken. 我正在尝试使用的循环:(如果购物车中的每个项目都可能附有建议的项目)for循环可以很好地工作,如果语句已损坏。

if(!empty($_SESSION["products"]->suggested)) {
echo '<div id="products-wrapper"><h1>Suggested Items</h1><div class="view-cart">';
echo '<table width="750" cellpadding="0" cellspacing="0" style="text-align:center;padding:5px;">';

        foreach ($_SESSION["products"] as $cart_itm)  
        {
        echo '<tr><td>'.$cart_itm['suggested'].' '.$cart_itm['suggestedtext'].'</td></tr>';
        }
echo '</table></div></div>';

}

You can "chain" keys or indexes of nested arrays just like you would access properties of an object 您可以“链接”嵌套数组的键或索引,就像访问对象的属性一样

$_SESSION["products"]["suggested"]

Should help you with your Problem 应该可以帮助您解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM