Best method for converting a PHP array to javascript

前端 未结 4 656
无人共我
无人共我 2020-12-03 19:39

I am passing a PHP array to a javascript function. The only way I know to do this is to create a js array from the PHP array and pass that to the js function. But this creat

相关标签:
4条回答
  • 2020-12-03 20:07

    Use JSON. see why JSON over XML: http://thephpcode.blogspot.com/2008/08/why-json-over-xml-in-ajax.html

    To use json in PHP simply:

    <?php
    
      echo '<script type="text/javascript">/* <![CDATA[ */';
      echo 'var train = '.json_encode($array);
      echo '/* ]]> */</script>';
    
    ?>
    

    the variable train in Javascript will be an object containing properties and arrays based on your PHP variable $array.

    To parse or iterate through the train object, you can use for ... in statements for JSON arrays, and directly use object.property for JSON objects.

    See this:

    <?php
    
      $array = array(array('id'=>3,'title'=>'Great2'),array('id'=>5,'title'=>'Great'),array('id'=>1,'title'=>'Great3'))
      echo '<script type="text/javascript">/* <![CDATA[ */';
      echo 'var train = '.json_encode($array);
      echo '/* ]]> */</script>';
    
    ?>
    

    The output will be:

     var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
    

    the variable train becomes an array of objects. [] squrare brackets are arrays, holding more arrays or objects. {} curly braces are objects, they have properties to them.

    So to iterate the train variable:

    <script type="text/javascript">
    
      var train = [{id:3,title:'Great2'},{id:5,title:'Great'},{id:1,title:'Great3'}];
    
      for(i in train){
        var t = train[i]; // get the current element of the Array
        alert(t.id); // gets the ID
        alert(t.title); // gets the title
      }
    
    </script>
    

    Simple! Hope that really helps.

    0 讨论(0)
  • 2020-12-03 20:08

    json_encode. See http://us3.php.net/manual/en/function.json-encode.php

    0 讨论(0)
  • 2020-12-03 20:22

    A more space-efficient way of encoding Javascript data structures is called JSON.

    As of PHP 5.2.0, you can use the following function to spit out some JSON: json_encode().

    0 讨论(0)
  • 2020-12-03 20:22

    You can always use XMLHttpRequest to load it as JSON or XML.

    0 讨论(0)
提交回复
热议问题