Reputation: 49
Which loop can I use for an array in array with the output like this:
Coffee 1,90 | 2,30
Tea 1,70 | 2,20
This is the array
<?php
Array ( [coffee] => Array (
[Small] => 1,90
[Big] => 2,30
)
[tea] => Array (
[Small] => 1,70
[Big] => 2,20
)
)
?>
I tried this
<?php
foreach ($array as $beverage => $types) {
echo $beverage;
foreach ($types as $type => $price) {
echo $price;
}
}
?>
But the output displays this
coffee 1,902,30
tea 1,702,20
How can I separate this like
Coffee 1,90 | 2,30
Tea 1,70 | 2,20
Upvotes: 1
Views: 64
Reputation: 23
foreach ($array as $beverage => $types) {
echo $beverage;
foreach ($types as $type => $price) {
if ($price == end($types)) {
echo $price."|";
}
else{
echo $price;
}
}
}
Have a look at this : https://www.geeksforgeeks.org/php-end-function/
Upvotes: 0
Reputation: 54841
foreach ($array as $beverage => $types) {
echo ucfirst($beverage) . implode(' | ', $types);
}
Upvotes: 4