最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php array loading into javascript - Stack Overflow

programmeradmin0浏览0评论

so I am a total php/javascript noob.

I'm trying load a full php array into a javascript array. I wrote this for Javascript:

    var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "<?php echo giveJS() ?>";
}

And this for php

static $counter = 0;

function giveJS() {
    global $names;
    global $counter;
    $counter++;
    return $names[$counter]; 
}

I already checked if the php array is correctly filled with data. When I write a output line in javascript, like

document.write(names[10]);

it only gives me the first entry in the php array so it seems like everytime the for loop is repeated its initialising the php file from scratch and so setting the counter to 0. How can i fix that?

so I am a total php/javascript noob.

I'm trying load a full php array into a javascript array. I wrote this for Javascript:

    var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "<?php echo giveJS() ?>";
}

And this for php

static $counter = 0;

function giveJS() {
    global $names;
    global $counter;
    $counter++;
    return $names[$counter]; 
}

I already checked if the php array is correctly filled with data. When I write a output line in javascript, like

document.write(names[10]);

it only gives me the first entry in the php array so it seems like everytime the for loop is repeated its initialising the php file from scratch and so setting the counter to 0. How can i fix that?

Share Improve this question edited Mar 25, 2019 at 14:05 Tim Daubenschütz asked Mar 19, 2012 at 16:38 Tim DaubenschützTim Daubenschütz 2,1736 gold badges23 silver badges41 bronze badges 1
  • Either static $counter = 0; (inside the function) or you use a global variable. – hakre Commented Mar 19, 2012 at 16:44
Add a comment  | 

6 Answers 6

Reset to default 9

In php

//Bla being the php array you want to give to javascript. Create it however you like
$bla = array();
$bla[] = 'cat';
$bla[] = 'dog';
$bla[] = 'bat';
echo '<script>var myarray = '.json_encode($bla) .';</script>';

The above code will then output a script tag contain a varible called myarray, then contents of which will be JSON specifying the above array (json_encode formats the array in to javascript internal syntax- the array will probably look like ['cat','dog','bat] )

You can then get values from the JavaScript array as so:

<script>
 console.log(myarray[2]);
</script>

Your PHP code is executed before your Javascript, thus it doesn't make sense to use it this way.

Instead, you should do something like this:

<?php for ($i=0;$i<48;$i++):?>
     name[<?php echo $i;?>] = "<?php echo giveJS();?>";
<?php endfor; ?>

In fact, if your PHP is that simple, you don't need a function:

<?php foreach ($names as $i=>$name):?>
    name[<?php echo $i;?>] = "<?php echo $name;?>";
<?php endforeah;?>

In both case, you'll have a Javascript like that:

name[0] = 'name0';
name[1] = 'name1';
...
name[47] = 'name47';

This is a common mistake for people starting web development. The important thing to realize is that all of your PHP code runs before the javascript starts*. If you take a look at the javascript that gets to the browser you'll see

    var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "foo";
}

which explains why each element is the same. A nicer way to do this is to use json_encode in PHP to just transfer the array into a JS variable. Like this:

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

*For the people writing comments about Javascript running at the same time as the PHP, either by starting the JS early or using AJAX, yes, I'm aware, but for a beginner the model of PHP totally generates then JS starts running is simpler to understand.

Let's say $names[1] is "Bob"..

Your PHP script will run on the server, outputting the following JavaScript:

var names = new Array();
for(var i = 0; i < 48; i++) {
    names[i] = "Bob";
}

which in turn will run in your browser (the client), creating an array names with 48 "Bob" elements.


There is no easy conversation between PHP and JavaScript. Either (1) your PHP script outputs everything that the JavaScript needs to know at the outset, or (2) you communicate with the server as needed using AJAX.

In your case JSONEncode is probably the best solution, as it will output the array in JavaScript Object Notation, removing the need for loop-based initialization.

Depends on how many dimension your array have. SHortest way for simple array:

 var names = new Array(<?php echo implode(',', $php_array);?>);

I think json_encode() is what you are searching for.

Example

<?php
$myArray = array('generating', 'some', 'items');
?>
<script type="text/javascript>
    var myArray = <?= json_encode($myArray); ?>;
</script>
发布评论

评论列表(0)

  1. 暂无评论