数组中的循环数组

时间:2019-04-16 11:42:18

标签: php arrays

我可以将哪个循环用于数组中的数组,其输出如下:

Coffee 1,90 | 2,30
Tea 1,70 | 2,20

这是数组

<?php
Array ( [coffee] => Array ( 
                    [Small] => 1,90
                    [Big] => 2,30
                ) 
    [tea] => Array ( 
                    [Small] => 1,70 
                    [Big] => 2,20 
                )
)
?>

我尝试过

<?php
foreach ($array as $beverage => $types) {
    echo $beverage;
  foreach ($types as $type => $price) {
    echo $price;
  }
}
?>

但是输出显示此

coffee 1,902,30
tea 1,702,20

我如何像这样

Coffee 1,90 | 2,30
Tea 1,70 | 2,20

2 个答案:

答案 0 :(得分:4)

foreach ($array as $beverage => $types) {
    echo ucfirst($beverage) . implode(' | ', $types);
}

答案 1 :(得分:0)

foreach ($array as $beverage => $types) {
    echo $beverage;
    foreach ($types as $type => $price) {
        if ($price == end($types)) {

            echo $price."|";
        }
        else{
            echo $price;
        }
    }
}

看看这个:https://www.geeksforgeeks.org/php-end-function/