Convert Multidimensional PHP array to javascript array

后端 未结 4 1228
灰色年华
灰色年华 2021-01-12 11:23

I\'m trying to convert a PHP multidimensional array to a javascript array using the JSON encoder. When I do a var_dump, my php array looks like this:

array (         


        
相关标签:
4条回答
  • 2021-01-12 11:41

    Just add single quotes in the js function,like

    var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');

    0 讨论(0)
  • 2021-01-12 11:58

    Do not use parseJSON, that's for a string. Just do:

    <?php
    $php_array = array ('Key'=>'a', 'Value'=>'asite.com');
    ?>
    <html>
    <head>
    
        <script type="text/javascript">
        var tempArray = <?php echo json_encode($php_array); ?>;
        console.log(tempArray);
        </script>
    </head>
    <body>
    </body>
    </html>
    

    This give me in the console:

    Object { Key="a", Value="asite.com"}
    
    0 讨论(0)
  • 2021-01-12 12:00

    This worked for me.

    <script type='text/javascript'>
    <?php
        $php_array = array(
            array("casa1", "abc", "123"), 
            array("casa2", "def", "456"), 
            array("casa3", "ghi", "789" )
        );
    
        $js_array = json_encode($php_array);
        echo "var casas = ". $js_array . ";\n";
    ?>
    
    alert(casas[0][1]);
    
    </script>
    
    0 讨论(0)
  • 2021-01-12 12:04

    You do not have to call parseJSON since the output of json_decode is a javascript literal. Just assign it to a variable.

    var tempArray = <?php echo json_encode($php_array); ?>;
    

    You should be able then to access the properties as

    alert(tempArray[0].Key);
    
    0 讨论(0)
提交回复
热议问题