How to convert my PHP array to Javascript array in laravel 4

in my controller I have an array that I populated from my database and saved, which looks like this and is called dataset2

    array(2) {
      ["April"]=> int(92)
      ["May"]=>  int(86)
    }

In my view, I can dd {{}} in an array and see that it is a structure.

Now I want to convert it to a javascript array so that I can use the fleet to turn it into a graph.

my javascript in my view is as follows

 <script language="javascript" type="text/javascript">
    $(function () {

        var data1 = [
            ["April", 13],
            ["May", 20],
         ];

   var data2 = [<?php echo json_encode($dataset2 );?>];

   $.plot("#placeholder", [{
       data: data1,
       label: "NewBeach"
   }, {
       data: data2,
       label: "Sandhills"
   }], {
       series: {
           lines: { show: true },
           points: {
              show: true,
              barWidth: 0.1,
              align: "center"
           }
       },
       xaxis: {
           mode: "categories"
       },
        yaxis: {
       },
       grid: { 
           hoverable: true, 
           clickable: true 
       }
   });
});
</script>

Is there something I am missing when converting ?, since it does not draw anything with the JSON_encode array, but does it with hard-coded. From what I read, it seems like that's all I need. Is it because of the values ​​in my array?

Regards Mike

+4
3

: var data2 =; []

, . array('key'=>'value')

$array = array(label=>value, name=>value);

var data2 = <?php echo json_encode($dataset2 );?>;
+6

. Laracasts laracasts/PHP-Vars-To-Js-Transformer

JavaScript::put('data2', $dataset2);
+5

php array associative array, javascript object:

array(2) {
  ["April"]=> int(92)
  ["May"]=>  int(86)
}
// Will be:
{
  "April": 92,
  "May": 86
}
// When you `json_encode` it.  

, data1 javascript, : php:

$array = Array(
  Array("April", 92),
  Array("May", 86)
);

, ( ) javascript json_encode.

+2

Source: https://habr.com/ru/post/1540530/


All Articles