i have this array
array (size=3)
1 =>
array (size=5)
'produs' =>
array (size=3)
0 => string 'prajitura cu nuca' (length=17)
1 => string 'prajitura cu morcovi' (length=20)
2 => string 'prajitura cu morcovi' (length=20)
'creatorchoise' => int 9
'ambalaj' => string 'caserola' (length=8)
'capacitate' => string '15' (length=2)
'cantitate' => string '1' (length=1)
2 =>
array (size=5)
'produs' => string 'prajitura cu nuca' (length=17)
'creatorchoise' => int 28
'ambalaj' => string 'platou' (length=6)
'capacitate' => string '30' (length=2)
'cantitate' => string '1' (length=1)
i want to echo out values so i made this
foreach ($_SESSION['cos'] as $key => $value){
$creatorchoise = $value['creatorchoise'];
$ambalaj = $value['ambalaj'];
$capacitate = $value['capacitate'];
$cantitate = $value['cantitate'];
if (!is_array($value['produs'])){
$produs = $value['produs'];
} else {
foreach ($value['produs'] as $row => $produs){
}
echo "produs: " . $produs . " /ambalaj: " . $ambalaj . " / capacitate: " . $capacitate . " / cantitate: " . $cantitate . "<br>";
}
the problem starts when the product is array, i know im echoing out of the product array loop
any sugestions?
You could coerce the string to an array:
<?php
$data =
[
[
'products' => 'Gold and shiny'
],
[
'products' => [
'Silver beads',
'Green emeralds'
]
]
];
foreach($data as $item) {
$products = (array) $item['products'];
foreach($products as $product) {
echo $product, "\n";
}
}
Output:
Gold and shiny
Silver beads
Green emeralds
If $produs
is an array, you should access the value inside the foreach
foreach ($value['produs'] as $row => $produs){
// access $produs here
}
If you want to echo all the values from the array using a delimiter, you could also use implode
$produs = "";
if (!is_array($value['produs'])){
$produs = $value['produs'];
} else {
$produs = implode(',', $value['produs']);
}
echo "produs: " . $produs . " /ambalaj: " . $ambalaj . " / capacitate: " . $capacitate . " / cantitate: " . $cantitate . "<br>";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.