Skip to content
Advertisement

PHP Multidimensional array number formatting returns A

I am having issue with number formatting of array elements. It always returns an “A” letter, no matter element value.

$tab = array_map(function ($string) {
    return preg_replace_callback( "/[0-9]+/", function ($matches) {
        return number_format($matches[0], 2, ',', ' ');
    }, $string);
}, $array);

I am calling for that value with adress $tab['VII']['B']['podatek']['PTUG'] An this is part of an Array:

$array = array(
        ...

        "VII" => array(
            ...
            "B" => array(
                ...
                "podatek" => array(
                    ...
                    "PTUG" => "789456123",

I am using tcpdf with this file as well, if that is making a trouble. What i need is to in proper fields call out for specific array elements and conver them to: 123 123,45 number format.

Also, would need to format date from yyyy-mm-dd to dd-mm-yyyy with addition of “r.” after the date.

Advertisement

Answer

You can use array_walk_recursive() to run through your array. Within the callback, add your different checks to modify the values in each case.

array_walk_recursive($array, function (&$val) {
    // Format integers
    if (filter_var($val, FILTER_VALIDATE_INT)) {
        $val = number_format($val, 2, ',', ' ');
    // Format dates
    } elseif (preg_match('/^d{4}-d{2}-d{2}$/', $val)) {
        $parts = explode('-', $val);
        $val = implode('-', array_reverse($parts));
    }
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement