Home > Net >  PHP: Print ordered array
PHP: Print ordered array

Time:03-15

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?

CodePudding user response:

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>';
}

CodePudding user response:

This is the result of your script :

Array ( [0] => Array ( [typ] => ovocna [amount] => ) [1] => Array ( [typ] => slana [amount] => ) [2] => Array ( [typ] => sladka [amount] => ) ) 

The error is that the $value you use in the foreach loop is an array so you can't use the echo function. To access the value of 'typ' and 'amount' you must use the following form $value ['typ'] and $value ['amount'].

  • Related