Search code examples
phpnumber-formatting

How to format numbers on multidimensional arrays in php?


Sorry, my question is probably an easy one, but I don't know PHP, and after hours of surfing the net, I couldn't make it work :/

I'm doing a website with a list of prices, that I put in an array:

$priceList = [
    "teaTowel" => [
        "calm500"   => 2.75,    "active500" => 3.25,
        "calm300"   => 3.15,    "active300" => 3.65,
        "calm150"   => 3.50,    "active150" => 4.00,
        "calm50"    => 3.90,    "active50"  => 4.40
    ],
    "apronChild" => [
        "calm500"   => 3.30,    "active500" => 3.45,
        "calm300"   => 3.70,    "active300" => 3.85,
        "calm150"   => 4.20,    "active150" => 4.35,
        "calm50"    => 4.90,    "active50"  => 5.05
    ]
];

I managed to display them (yay !), like so:

<p>Price: <?php echo $priceList['apronChild']['calm500'] ?> &euro;</p>

The problem is, I would like to format the prices so that they appear with a comma instead of a point, and two decimals. Like "3,30" instead of "3.3"

But I can't make the function format_number work on my array :/

I tried endless variations of this:

$priceListFormat = array_map(function($num){return number_format($num, 2, ',', ' ');}, $priceList);

<p>Price: <?php echo $priceListFormat['apronChild']['calm500'] ?> &euro;</p>

But there's no way around it, I know nothing about php and I'm kind of stumbling in the dark here ^^ Thanks for your help !


Solution

  • You can't do this with array_map(), because it doesn't return an associative array. You have to use nested loops.

    $priceListFormat = [];
    foreach ($priceList as $k1 => $v1) {
        $r1 = [];
        foreach ($v1 as $k2 => $v2) {
            $r1[$k2] = number_format($v2, 2, ',', ' ');
        }
        $priceListFormat[$k1] = $r1;
    }