assigning multidimensional php array to javascript array

前端 未结 5 1581
梦如初夏
梦如初夏 2021-01-17 02:29

I know this may be a duplicate, but I cant wrap my brain around the other examples. Help would be appreciated. I have a php array that i need to assign to a javascript array

相关标签:
5条回答
  • 2021-01-17 03:02
    1. You can't use numbers as variable names in javascript.
    2. You don't need to use "var" with each line. Something like

      var test = [];
      test[1] = 'some value';
      test[2] = 'some value';
      
    3. You probably want to look at using the JSON_ENCODE function from PHP

    0 讨论(0)
  • 2021-01-17 03:03

    The way you are working with arrays is not correct.

    First you should initialize the array:

    var myArr = [];
    

    Then if you just want to add to the array, you can use push:

    myArr.push("something");
    

    or to a specific index:

    myArr[11] = "something";
    

    The syntax you are using is completely invalid.

    0 讨论(0)
  • 2021-01-17 03:07
    <?php
        if (!func_exists('json_encode')) die('sorry... I tried');
        $buffer = array();
        while ($value = mysql_fetch_assoc($result)) {
            $buffer[] = $value;
        }
        echo "<script>var data = ".json_encode($buffer)."</script>";
    ?>
    <script>
    console.log(data);
    </script>
    

    Requires PHP 5.2.0

    0 讨论(0)
  • 2021-01-17 03:16

    You cannot use an integer as a variable name, like in this line: print "var 25[".$i."]=" .$result1['25'].";\n";. 25 cannot be a variable.

    If you want to map an array to a javascript object, you might want to take a look at json_encode

    EXAMPLE
    Your code could be written like this:

    <?php
    $result = array();
    
    while ($row = mysql_fetch_array($query1)){
      $result[] = $row;
    }
    ?>
    <script>
      var result = <?= json_encode($result); ?>;
      alert (result[1][500]);
    </script>
    

    looks much cleaner to me.

    0 讨论(0)
  • 2021-01-17 03:18

    Your code is wrong because of what is generated by PHP (especially because you use numbers as variable names in JavaScript, plus you define the same variables with each loop).

    To simplify what you want to achieve, just create some variable in PHP and assign a value to it. Lets call it eg. $my_proxy_var.

    Then pass it to JavaScript like that (within some <script> tag):

    var myProxyVar = <?php echo json_encode($my_proxy_var); ?>;
    

    Just remember that:

    • non-associative array in PHP becomes simple array in JavaScript,
    • associative array in PHP becomes object in JavaScript,

    This is important so you can avoid confusion and chose between non-associative and associative array on each level.

    You can test the code on this codepad.

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