472,146 Members | 1,308 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,146 software developers and data experts.

parsing php array to javascript

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
16 9087
Dormilich
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
@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
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
is there any chance that would work?
Oct 28 '09 #6
gits
5,390 Expert Mod 4TB
@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
8,658 Expert Mod 8TB
@freefony
nope, you’d end up redeclaring 2 variables

@gits: looks like that.
Oct 28 '09 #8
gits
5,390 Expert Mod 4TB
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
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
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
@didoamylee
it doesn't. because the PHP array is associative and javascript arrays are always numeric.
Oct 29 '09 #13
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
8,658 Expert Mod 8TB
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
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
8,658 Expert Mod 8TB
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.

Similar topics

5 posts views Thread by Sandman | last post: by
11 posts views Thread by Sven Neuberg | last post: by
4 posts views Thread by ralphNOSPAM | last post: by
3 posts views Thread by djdave | last post: by
3 posts views Thread by Aaron | last post: by
6 posts views Thread by Jasper | last post: by
1 post views Thread by Philip Semanchuk | last post: by
reply views Thread by Saiars | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.