dsf323233323332 2013-12-05 15:27
浏览 122
已采纳

php循环遍历数组 - 输出数组值和键

I have the following array structure in place that i have to keep as it's an existing website:

$label_options = array(
    "label_size" => 'A4',
    "label_position" => 'Top',
    "label_qty" => 50
);

$ink_options = array(
    "black" => 1,
    "colour" => 0
);

$item = array(
    "item_number" => 12546518,
    "item_type" => 'Canon',
    "item_label_options" => $label_options,   
    "item_ink_options" => $ink_options,
    "item_qty" => 2,      
    "item_price" => 13.99,
    "item_total" => 26.98,
    "item_delivery" => 2.49
);

if (isset($_SESSION['cart'])) {
    $_SESSION['cart'][$unique] = $item;
} else {
    $_SESSION['cart'] = array($unique => $item);
}

I now want to be able to output the values inside the arrays and the arrays inside the array. I can use the below:

foreach ($_SESSION['cart'] as $unique => $item) {
    print 'Item Number = '.$item['item_number'].'<br />';
    print 'Qty = '.$item['item_qty'].'<br />';
    print 'Price = '.$item['item_price'].'<br />';

    foreach ($item['item_label_options'] as $key => $option) {
       print $option['label_size'].'<br />';
       print $option['label_position'].'<br />';
       print $option['label_qty'].'<br />';
    }
}

which successfully outputs the first loop but not the second - just putting the first letter of each:

Item Number = 12546518
Qty = 1
Price = 7.99

A // should be A4
T // should be Top
5 // should be 50

Also is there a way i can loop and output all the values without having to actually write 'Item Number = ... it can just output each key with its value as i won't always know how many and what the names of each one are?

  • 写回答

3条回答 默认 最新

  • doushi1847 2013-12-05 15:55
    关注

    In your inner foreach loop, the keys label_size, label_position and label_qty don't exist. When a key doesn't exist, I guess it's defaulting to 0 and as a result just gives you the first letter. This will produce what you want:

    foreach ($_SESSION['cart'] as $unique => $item) {
        print 'Item Number = '.$item['item_number'].'<br />';
        print 'Qty = '.$item['item_qty'].'<br />';
        print 'Price = '.$item['item_price'].'<br />';
        foreach ($item['item_label_options'] as $key => $option) {
           print $option.'<br />';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,