PHP: Print ordered array

Issue

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?

Solution

One way, simply address the $value array using its members

foreach($kosik as $key => $value) { 
    echo "$key - $value[typ], $value[amount] <br>";  
}

NOTE that inside a double quoted string you address the array slightly differently, you dont use the quotes around the occurance name.

Possibly more flexibly you could use a double loop, specially if you dont know or cannot guarantee the occurances will always be there

$str = '';
foreach($kosik as $key => $value) { 
    $str .= "$key - ";
    foreach ( $value as $val ) {
        $str .= "$val, ";
    }
    $str = rtrim($str, ', ');  remove trailing comma
    $str .= '<br>';
}

Answered By – RiggsFolly

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.