Home > Software engineering >  PHP Convert multidimensional array to a string (LITERALLY)
PHP Convert multidimensional array to a string (LITERALLY)

Time:08-12

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

CodePudding user response:

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));
  • Related