dongyan4424
dongyan4424
2017-12-17 17:12

在js对象中插入转换后的Php数组

已采纳

I have a php array that i converted in Js using the json_encode method:

$mesi = ['Nov', 'Dic'];

var js_mesi = '<?php print(json_encode($mesi)); ?>';

this is the converted array

["Nov","Dic"]

The problem I'm having now it's to place the Js array inside a JS object like this

data: {
    labels: [js_mesi],
}

because the values of js_mesi are recognized as a single value and not as two separate values. The output I would like to have is this:

data: {
    labels: ["Nov", "Dic"]
}

instead I see this

data: {
    labels: ["Nov,Dic"]
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douchuxun4162 douchuxun4162 4年前

    In the javascript variable assignment, you had added ' single quotes around the PHP block.

    Hence it was considered as a string and would have got the value '["Nov","Dic"]' instead of an array.

    Corrected code

    <?php
    $mesi = array('Nov','Dic');
    ?>
    
    var js_mesi = <?php print(json_encode($mesi)); ?>;
    

    Output

    var js_mesi = ["Nov","Dic"];
    

    Refer https://eval.in/920653 for the output

    点赞 评论 复制链接分享