Best method for converting a PHP array to javascript

前端 未结 4 664
无人共我
无人共我 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条回答
  •  Happy的楠姐
    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:

    /*  */';
    
    ?>
    

    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:

    3,'title'=>'Great2'),array('id'=>5,'title'=>'Great'),array('id'=>1,'title'=>'Great3'))
      echo '';
    
    ?>
    

    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:

    
    

    Simple! Hope that really helps.

提交回复
热议问题