简体   繁体   中英

How to format a php array into a javascript array?

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 ?

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

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>

使用这个,肯定会起作用

<?php echo json_encode($array) ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM