0

I have a 3D array in php when using var_dump($arr) it looks like this

array(2) { 
[0]=> array(4) { 
  [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } 
  [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } 
  [2]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(2) } 
  [3]=> array(2) { [0]=> string(7) "28.5714" [1]=> int(10) } 
} 

[1]=> array(3) { 
   [0]=> array(2) { [0]=> string(7) "18.1818" [1]=> int(10) } 
   [1]=> array(2) { [0]=> string(7) "18.1818" [1]=> int(9) } 
   [2]=> array(2) { [0]=> string(6) "0.0000" [1]=> int(6) } 
} 


} 

I want to get it in this format in javascript:

var data = [
                [
                  {x:36, y:8, r:10},{x:27, y:5, r:10},{x:36, y:2, r:10},{x:28, y:10, r:10}
                ],
                [
                  {x:18, y:10, r:10},{x:18, y:9, r:10},{x:0, y:6, r:10}
                ]
            ];

Where x is the [0] index of innermost array and y is [1] index of innermost array r is always 10

How do i format it in this way ?

1
  • You can loop through the array and process data, generate a string and then echo that string, Commented Jan 24, 2018 at 11:05

3 Answers 3

1

Try this:

echo  json_encode($arr);

or if you are building your json string manually make sure to use the following in your front JS:

var json = JSON.parse(data);
1
  • Other way around, you would json_decode a json string that you received from a http request. to print to javascript you would json_encode the php array. Commented Jan 24, 2018 at 11:18
0

You could format the data then echo the result as a javascript variable.

<?php

$data = [
  [
    [ "36.3636", 8 ],
    [ "27.2727", 5 ],
    [ "36.3636", 2 ],
    [ "28.5714", 10 ],
  ],
  [
    [ "18.1818", 10 ],
    [ "18.1818", 9 ],
    [ "0.0000", 6 ],
  ]
];

// reformat the data in php to your desired format
$formatted = array_map(function($coords) {
  return array_map(function($item) {
    return [
      'x' => (int) $item[0],
      'y' => (int) $item[1],
      'r' => 10,
    ];
  }, $coords);
}, $data);

?>
<!-- echo json encode your formatted data as a javascript variable -->
<script>var data = <?=json_encode($formatted, JSON_NUMERIC_CHECK)?>;</script>
<script>console.log(data)</script>
0

Use this, it will definitely work

<?php echo json_encode($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.