By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,650 Members | 1,823 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,650 IT Pros & Developers. It's quick & easy.

parsing php array to javascript

P: 59
Am trying to parse a php array into javascript but i found that only one element of the array was present in the javascript array. here is my code code
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. include("../../connect.php");
  3. $qry="select * from stock";
  4. $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
  5. while($row=mysql_fetch_assoc($rst)){
  6.     $item=$row['item'];
  7.     $list[$item]=$row['price'];
  8. }
  9. foreach($list as $key =>$value){
  10.     echo $key."-";
  11.     echo $value."<br/>";
  12. }
  13. echo $list['coke'];
  14. ?>
  15. <script type="text/javascript" language="javascript">
  16. list = new Array("<?php echo $list[$item]; ?>")
  17. alert(list);
  18. </script>
  19.  
the foreach loop worked just fine printing all the keys and values in the database but in the process of parsing it i seem to be doing something wrongly
cos the alert is only printing the value the last key "5000"
Oct 28 '09 #1
Share this Question
Share on Google+
16 Replies


Dormilich
Expert Mod 5K+
P: 8,639
the problem is that a Javascript array is somewhat different from a PHP array. a Javascript array uses only numeric values as key. or put in other words, there is no such thing as an associative array in Javascript.

an associative array in Javascript is called: object. you have several options to define a (standard) object
- using the Object Literal
Expand|Select|Wrap|Line Numbers
  1. var obj_name = {
  2.     key1 : value1,
  3.     key2 : value2
  4. // etc.
  5. }
- create an object with “new”, applicable if you have a predefined set of keys
Expand|Select|Wrap|Line Numbers
  1. function MyObject(value)
  2. {
  3.     this.key = value;
  4. }
  5. var obj_name = new MyObject("a value");
- create a new empty object and append the values
Expand|Select|Wrap|Line Numbers
  1. var obj_name = new Object;
  2. obj_name.key1 = value1;
  3. obj_name.key2 = value2;
  4. // etc.
and regarding the output. calling $list[$item] is exactly one value.
Oct 28 '09 #2

P: 59
i think i uderstand the 1st and last options but the array is being generated by values from a table in the database and i have no control over the size of the array and worse i dont think javascript have the foreach loop equivalent
Oct 28 '09 #3

Dormilich
Expert Mod 5K+
P: 8,639
@freefony
wrong.

nevertheless, it doesn’t matter. since PHP long finished execution when JavaScript starts, you have to print each and every key - value combination by PHP (using method 1 or 3 (2 was for completeness))
Oct 28 '09 #4

P: 59
Expand|Select|Wrap|Line Numbers
  1. echo "<script languege='javascript'>";
  2. foreach($list as $key=>$val){
  3.  echo "var item=".$key;
  4.  echo "var price=".$val;
  5. }
  6. echo "</script>";
  7.  
Oct 28 '09 #5

P: 59
is there any chance that would work?
Oct 28 '09 #6

gits
Expert Mod 5K+
P: 5,320
@Dormilich
wouldn't that be similar to:

Expand|Select|Wrap|Line Numbers
  1. echo 'var obj_name = '.json_encode($php_array);
  2.  
kind regards
Oct 28 '09 #7

Dormilich
Expert Mod 5K+
P: 8,639
@freefony
nope, you’d end up redeclaring 2 variables

@gits: looks like that.
Oct 28 '09 #8

gits
Expert Mod 5K+
P: 5,320
i did ... and i thought ... even when i'm not a php-expert that for the current case:

Expand|Select|Wrap|Line Numbers
  1. echo 'var list = '.json_encode($list);
could do the job? it should create a string that is later on evaled by JavaScript as an object (or assoc array if you want to call it that) with all keys and values in the $list array?

kind regards
Oct 29 '09 #9

P: 59
Hey the jason function is a powerful tool! but little problem tho i still cant get the javascript array.
Expand|Select|Wrap|Line Numbers
  1. //these two lines works perfectly
  2. $mylist=jason_encode($list);
  3. var_dump($mylist);
  4. //output: string(64) "{"coke":"70","Emzor Paracetamol BP":"2","Paracetamol BP":"5000"}" 
but the following codes return nothing what am i doing wrong?
Expand|Select|Wrap|Line Numbers
  1. echo "<script languege='javascript'>";
  2. echo "var mylist=".json_encode($list);
  3. echo "document.write(mylist)";
  4. echo "var data=eval(mylist)";
  5. echo "</script>";
  6.  
Oct 29 '09 #10

Dormilich
Expert Mod 5K+
P: 8,639
1. you don’t have an Array
2. what do you expect document.write(mylist) to output?*

* from the JavaScript Point-of-View, it outputs the variable’s string representation (for object it’s the toString() method’s return value)

PS. had a look in Firebug, the object was created as desired
PPS. there’s a typo on line 1 and you really should use the type attribute there
Oct 29 '09 #11

didoamylee
P: 16
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. var a = new Array('<?php echo implode("','",$php_array); ?>');
  3. </script>
  4.  
That should do the trick.
Oct 29 '09 #12

Dormilich
Expert Mod 5K+
P: 8,639
@didoamylee
it doesn't. because the PHP array is associative and javascript arrays are always numeric.
Oct 29 '09 #13

P: 59
Ok guys! i got working
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $qry="select * from stock";
  3. $rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
  4. while($row=mysql_fetch_assoc($rst)){
  5.     $item=$row['item'];
  6.     $list[$item]=$row['price'];
  7. }
  8. ?>
  9. <script type="text/javascript" language="javascript">
  10. var list=new Array('<?php echo json_encode($list); ?>');
  11. document.write(list);
  12.  
  13. </script>
  14.  
this suits my purpose and would solve a lot of problems i ve been facing with jscript and php arrays thanks to u guys
Oct 30 '09 #14

Dormilich
Expert Mod 5K+
P: 8,639
but you know that you sacrifice your PHP array keys with this?

how to do print_r() in Javascript
Expand|Select|Wrap|Line Numbers
  1. var my_php_array = { //… } // from json_encode()
  2. my_php_array.toString = function()
  3. {
  4.     var str = "";
  5.     for (var key in this)
  6.     {
  7.         str += key+" => "+this[key]+"\n";
  8.     }
  9.     return str;
  10. }
  11. div.innerHTML = my_php_array;
Oct 30 '09 #15

P: 59
even with the toString function above javascript still sees my php_array as just on element of the list array what can i do to solve that problem?
Nov 3 '09 #16

Dormilich
Expert Mod 5K+
P: 8,639
do not use new Array()
Nov 3 '09 #17

Post your reply

Sign in to post your reply or Sign up for a free account.