0

I have a PHP multidimensional array that looks like this:

[[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]]

(Those numbers are stored as strings, not int)

What I want is to convert this multidimensional array to a string that teorically is stored like this:

$converted = "[[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]]";

Literally all the array in one string

currently I have the array stored in a variable named $array

1 Answer 1

1

Use json_encode,

$array = [[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]];
echo json_encode($array);

And if your numbers is string, you can convert them to int before json_encode,

$array = [["1", "45"], ["2", "23"], [3, 37], [4, 51], [5, 18], [6, 32], [7, 29], [8, 45], [9, 37], [10, 50]];
echo json_encode(array_map(function ($subArray) {
    return array_map(function ($number) {
        return intval($number);
    }, $subArray);
}, $array));
Sign up to request clarification or add additional context in comments.

1 Comment

You can also simplify the entire expression to the following inliner: echo json_encode(array_map(fn($item) => array_map('intval', $item), $array));

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.