简体   繁体   中英

How to build JS array from PHP array and return to string?

I am trying to built a JS String array from a PHP String array, but my JS skills are a bit limited. I would like also display and return a selected JS row to a HTML or PHP string. Is it possible?

I would appreciate any help.

PHP part (working):

$i = 0;
while($row = mysql_fetch_array($result)){ //get data from a mysql table.
    $data = $row["sql_row"]; // string built
    echo "<script language=javascript>buildarray($i,$data)</script>";  //call the JS function
    $i = $i +1;
  }

Javascript part1:

<script type="text/javascript"> 
var myArray=new Array();
    function buildarray(id, text){
       myArray[id]=text;
    }
</script>

Javascript part2:

<script type="text/javascript"> 
function displayreturn(id){ 
    document.write(myArray[id]);  //dpisplay the data in the row number "id"
            return myArray[id];  //return the string
    }
</script>

Thank you in advance.

To create a working javascript array, there is a function in php available. its called json_encode , only available in php5.3 though. just call

<?php
$i = 0;
while($row = mysql_fetch_array($result)){ //get data from a mysql table.
    $php_array[$row["row1"]] = $row["Row2"];
    $i = $i +1;
}
$js_array = json_encode($php_array);

to your code above: you cant call javascript functions in php. they are called on different side. php on server, js on client.

You can pass the string from the php to the javascript and then use split function to create an array of letters from that string.

I would do it like this

<script type="text/javascript">
    var arrStr =[];
    <?php

    i = 0;
    while($row = mysql_fetch_array($result)){ //get data from a mysql table.
        $data = $row["row1"] . $row["Row2"]; 
        echo "arrStr.push('$data')";
      }
    ?>
</script>

Sorry about my php. Didn't write in it for a long time. Hope this helps.

PS Sorry got it wrong.

Are you trying to call a Javascript function from PHP? (That won't work). If I got you right this is what you want (to get the array from PHP to JS)

var myArray = new Array(); // JS array

<?php
    $i = 0;
    while ($row = mysql_fetch_array($result)) // get data from a mysql table.
    {
        $data = $row["row1"] . $row["Row2"];
        echo "myArray.push('$data');\n"; // push to the JS array
        $i = $i + 1;
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM