-2

I have tried to implement PHP array into JavaScript but the problem is that it is not converting properly.

For example if PHP array $new_array has a value of a,q,s,t,u it is assigning to all the indexes of JavaScript array for example:

js_array[0]=a,q,s,t,u;
js_array[1]=a,q,s,t,u;
js_array[2]=a,q,s,t,u;
js_array[3]=a,q,s,t,u;
js_array[4]=a,q,s,t,u;
js_array[5]=a,q,s,t,u;

This is my PHP code:

    $new_array = array(); // create a new array
$sql=mysql_query("SELECT * FROM animate ORDER BY RAND() LIMIT 5") or die("query Field");

 while($row=mysql_fetch_array($sql)){

    $new_array[] = $row['code'];

 }

js code

var array =[<?php echo json_encode($new_array);?>];
        alert(array[0]);
   for(var i=0; i <=9 ; i++)
        {
            array[i]=[<?php echo json_encode($new_array);?>];
    }

I want to assign values like:

array[0]=a;
array[1]=q;
array[2]=s;
array[3]=t;
array[4]=u;   

I want to do in this pattern but it is not working.

cweiske
  • 30,033
  • 14
  • 133
  • 194
mod geek
  • 310
  • 2
  • 18
  • What is in `$row['code']`??? – AbraCadaver Apr 21 '16 at 17:46
  • 1
    `[]` is creating an array with your encoded array in it, which you then store in ANOTHER array. all you need is `var arr = `; – Marc B Apr 21 '16 at 17:48
  • can you answer the question @MarcB with a proper code – mod geek Apr 21 '16 at 17:49
  • not working @MarcB – mod geek Apr 21 '16 at 17:50
  • 1
    not workin g**HOW**? Like I said, if you just want to embed that array of values you built in php to a var in javascript, then ALL you need is the one line I posted above. everything is just creating a bigger array with multiple copies of your from-db array in each element. – Marc B Apr 21 '16 at 17:53
  • I think you may wish to look up Javascript's comma operator. I think `js_array[0]=a,q,s,t,u;` is not doing what you think it is doing – Ed Heal Apr 21 '16 at 17:57

2 Answers2

4

You could "implode" it or you could use JSON.

Implode Method

var array = [<?php echo implode($array, ","); ?>];

JSON Method

var array = <?php echo json_encode($array); ?>;
Community
  • 1
  • 1
Dustin Poissant
  • 3,201
  • 1
  • 20
  • 32
0

Just iterate the php array inside the js array braces.

var array =[<?php foreach ($newArray as $value) echo "'" . $value . "',"; ?>];

You might have to put an additional line to clip the last ,

Charlie
  • 22,886
  • 11
  • 59
  • 90