如何将php数组格式化为javascript数组?

时间:2018-01-24 11:00:44

标签: javascript php arrays

3D array使用php时,var_dump($arr)显示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) } } }

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}
                ]
            ];

我想在javascript中以这种格式获取它:

x

其中[0] index是最内层数组的y[1] index最内层数组r的{​​{1}}始终为10

我如何以这种方式格式化它?

3 个答案:

答案 0 :(得分:1)

试试这个:

echo  json_encode($arr);

或者如果要手动构建json字符串,请确保在前面的JS中使用以下内容:

var json = JSON.parse(data);

答案 1 :(得分:0)

您可以格式化数据,然后将结果作为javascript变量回显。

<?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>

答案 2 :(得分:0)

使用它,它肯定会起作用

<?php echo json_encode($array) ?>