How to create and deploy masks for CPF, CNPJ, Data and Values?

Asked

Viewed 3,540 times

0

I tried to follow some examples of masks but I could not integrate in my code... someone could help me?

<table style="width: 100%" border="0">
    <thead>
        <tr style="text-align: left;">
            <th>Data</th> // Data ta retornando assim: 2019-03-28T00:00:00
            <th>Valores</th> // Valores esta retornando assim: 4688.86
            <th>CPF</th> // Mascara para CPF
            <th>CNPJ</th> // Mascara para CNPJ

        </tr>

    </thead>
<tbody>
<?php

    foreach ($json_data["Result"] as $data) {
    foreach ($data["CreditData"][0]["Occurrences"][0]["Details"] as $details) {

        echo '<tr>';
        echo '<td>' .$details["ExpiringDate"].'</td>'; // preciso da data 01/01/2019
        echo '<td> R$: ' .$details["Value"].'</td>'; // preciso do valor R$ 111.111.111,00
        echo '<td> R$: ' .$details["cpf"].'</td>'; //  Retornando CPF
        echo '<td> R$: ' .$details["cnpj"].'</td>'; // Retornando CNPJ
        echo '</tr>';
    }
}   
?>
</tbody>
</table>

In case of value my return line is:

// echo '<br>Valor Total em Ocorrencias: R$ ' .$data["CreditData"][0]["TotalDebts"]; 
echo number_format($data["CreditData"][0]["TotalDebts"], 2, ",", ".");

But it didn’t work, the disabled line works my return R $ 111111111.00

2 answers

4


You need three types of masks:

CPF/CNPJ:

function mask($val, $mask) {
    $maskared = '';
    $k = 0;
    for($i = 0; $i<=strlen($mask)-1; $i++) {
        if($mask[$i] == '#') {
            if(isset($val[$k])) $maskared .= $val[$k++];
        } else {
            if(isset($mask[$i])) $maskared .= $mask[$i];
        }
    }
    return $maskared;
}

$cpf = mask($details["cpf"], '###.###.###-##');
$cnpj = mask($details["cnpj"], '##.###.###/####-##');

Money:

number_format($details["Value"], 2, ",", ".");

Date:

$data = date('d/m/y', strtotime($details["ExpiringDate"]));

0

For the date, you can use this code date('d/m/Y', strtotime('2019-03-28T00:00:00'));, if the date is coming to you with string.

I believe this link will help you build the numeric values you need: Masks in PHP

  • Gabriel Roberto.. was worth the tip.... Date and Time I managed to put the Mascara.... but for the value not achieve... I edited my question for the friend view how is my value return line...

  • @Marcosrs, checks what type of value is being returned, you may need to convert the value to float, if it is a string, for this you can use the floatval function()

  • Gabriel, I got it... it worked. Tell me something and to put mask in zip code and phone? has an example...different from the example of the site the friend indicated, or can I follow the same logic as the CPF? $cep = Mask($Details["cep"], '#####.###');

  • Can follow the same logic of Cpf even, it is good that you already have the function ready.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.