Format number in array within an array_sum

353 Views Asked by At

I have a view in a laravel project where I have to print the sum of some array columns.

I Have this kind of code to achieve the result:

@foreach($data as $row)

.......

  @foreach($row as $key => $value)

   @if(in_array($key, ['PARZ. IN', 'PARZ. OUT', 'LORDO', 'PREU', 'AAMS', 'RETE ESER.',
                     'RETE OPER.', 'NETTO', 'UTILE ESER.', 'UTILE GEST.']))

    <th style="padding: 1em 0; background-color: #D9EDF7" class="text-center">

       {!! number_format(array_sum( array_column($data, $key)),2, ',', '.') !!} €

    </th>

   @else

    <th style="padding: 1em 0; background-color: #D9EDF7" class="text-center"></th>

   @endif

  @endforeach

@endforeach

It works fine. But there is a problem.

The numeric columns have a formatted italian currency number like this:

1.267,76 €

So the sum is printed wrong, because numbers have wrong format to perform the sum.

How can format all the numbers to 1267.76 before performing the sum within blade view?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

Ok, I'm trying to find the solution from yesterday. Now I found it on myself few minutes after I posted the question.

I modified the code to get the sum in this way:

{!! number_format(array_sum( str_replace([' €', '.', ','], ['', '', '.'],
                                    array_column($data, $key)) ),2, ',', '.') !!} €

Using str_replace with array_column the formatted currency numbers were replaced with standard numbers. Then number_format print the sum with original format.