PHP array to javascript array

前端 未结 4 1004
逝去的感伤
逝去的感伤 2021-01-29 00:47

Suppose, I have this array in php

$cities=array(
    \"Caracas\"=>array(
        \"air\"=>array(
            \"4\",\"3-5 Working Days\",\"Saturday\"
               


        
相关标签:
4条回答
  • 2021-01-29 01:03

    You can use json_encode to convert the array to JSON:

    echo json_encode($cities);
    exit;
    
    0 讨论(0)
  • 2021-01-29 01:03

    PHP

    echo json_encode($cities);
    

    jQuery

    $.getJSON("php_file.php",function(data) {
        // "data" is the echoed encoded array from the php file.
    
        // "array"."city name"."'air' or 'sea'"."number value that is in the PHP file"
        data.Caracas.air.4 // this is how you access the data inside the array
    });
    
    0 讨论(0)
  • 2021-01-29 01:07

    Try json_encode(). JSON is the first, best, and only answer for php<->javascript data transfers.

    0 讨论(0)
  • 2021-01-29 01:16
    <script>var cities = <?php echo json_encode($cities); ?>;</script>
    

    then to access the data

    <script>
      cities['San Mateo']['Air'][0]; // 4
      cities['San Mateo']['Air'][1]; // 3-5 Working Days
      // etc
    
      // looping
      for( var key in cities) {
        // key = city name
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题