Search code examples
javascriptphpblockly

Pushing a PHP array values into the JavaScript array?


I am working with Blockly to make some Blocks. All the errors came up when I am making Blockly Blocks. IS there anyone who knows why my code is not working in Blockly?

I have a URL including a set of JSON code. I got the content in a myPhp.php file using:

$data = file_get_contents("URL");

and then, I decode the data using:

$objects = json_decode($data, true);

$objects contains:

[0] => Array
        (
            [name] => Light
            [x] => 5
            [h] => 5
            [y] => 5
            [status] => on
        )

Now I want to push this array of data into a JavaScript array using:

<script type="text/javascript">
    var obj = new Array();
    <?php 
     foreach($objects as $key => $value){ 
    ?>
    obj.push('<?php echo $value; ?>');
    <?php } ?>
</script>

And $value needs to have all those data.

But I am getting Invalid or unexpected token JavaScript error. and when I look at to the source code, it shows the error is related to this line: obj.push and it says obj.push('<br /> <b>Notice</b>: Array to string conversion in <b>myPhp.php</b> on line <b>20</b><br /> Array');.


Solution

  • Your $value itself is an array and here your $key is 0.

    $key

     [0] => 
    

    $value

     Array
        (
            [name] => Light
            [x] => 5
            [h] => 5
            [y] => 5
            [status] => on
        )
    

    So you need another loop for $value to obtain each value like thus

    <script type="text/javascript">
     var obj = new Array();
    <?php 
     foreach($objects as $key => $value){ 
       foreach($value as $key1 => $value1){
     ?>
     obj.push('<?php echo $value1; ?>');
     <?php } }?>
    </script>