I have a simple PHP code where values from the array are ordered from largest to lowest.
I need them to print like basic HTML values with loop.
MY CODE:
$kosik = [
[
"typ" => "ovocna",
"amount" => $ovocnaNUM
],
[
"typ" => "slana",
"amount" => $slanaNUM,
],
[
"typ" => "sladka",
"amount" => $sladkaNUM
]
];
usort($kosik, function ($a, $b) {
return $b["amount"] - $a["amount"];
});
I need to echo them but when I use this I'ev got error:
foreach($kosik as $key => $value) {
echo "$key - $value <br>";
}
ERROR: Array to string conversion
But when I use this:
foreach($kosik[0] as $key => $value) {
echo "$key - $value <br>";
}
I've got no errors but only the first value is printed.
Is there any option how I can print all values with foreach or loop like is printed one value in code above?
My Answer:
You are close, but you need to access the values within each sub-array in your foreach loop. Here is the corrected code:
php
foreach($kosik as $item) {
foreach($item as $key => $value) {
echo "$key - $value
";
}
}
This will loop through each sub-array in `$kosik` and then loop through each key-value pair within that sub-array to print them out in HTML format.
Rate this post
3 of 5 based on 6795 votesComments