0

I have an array. Looks like this:

[
    {
        "id": "2",
        "number": "2",
        "debtor_number": null,
        "name": "Ziegler",
        "firstname": "Lisa",            
        "credit": "0.00",
    },
    {
        "id": "3",
        "number": "3",
        "debtor_number": null,
        "name": "Ziegler",
        "firstname": "Lisa",            
        "credit": "51.20",

Is there a posibility convert all numeric fileds like 2 or 51.20 to ints and floats respectively (I mean not manually) ?

Manually I do it this way:

             foreach ($array as &$val) {
                    foreach ($val as &$value) {
                        if(is_numeric($value)){
                            if(ctype_digit($value))
                                $value= (int)$value;
                            else
                                $value = (float)$value;
                        }
                    }
                }

1 Answer 1

1

If the depth of your array can vary and you want it to work for all levels, you can use array_walk_recursive():

array_walk_recursive($arr, function(&$val) {
    if (is_numeric($val)) {
        if (ctype_digit($val)) {
            $val= (int) $val;
        } else {
            $val = (float) $val;
        }
    }
});

An example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.