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 -
<?php
-
include("../../connect.php");
-
$qry="select * from stock";
-
$rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
-
while($row=mysql_fetch_assoc($rst)){
-
$item=$row['item'];
-
$list[$item]=$row['price'];
-
}
-
foreach($list as $key =>$value){
-
echo $key."-";
-
echo $value."<br/>";
-
}
-
echo $list['coke'];
-
?>
-
<script type="text/javascript" language="javascript">
-
list = new Array("<?php echo $list[$item]; ?>")
-
alert(list);
-
</script>
-
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"
16 9260
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 - var obj_name = {
-
key1 : value1,
-
key2 : value2
-
// etc.
-
}
- create an object with “new”, applicable if you have a predefined set of keys - function MyObject(value)
-
{
-
this.key = value;
-
}
-
var obj_name = new MyObject("a value");
- create a new empty object and append the values - var obj_name = new Object;
-
obj_name.key1 = value1;
-
obj_name.key2 = value2;
-
// etc.
and regarding the output. calling $list[$item] is exactly one value.
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
@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))
-
echo "<script languege='javascript'>";
-
foreach($list as $key=>$val){
-
echo "var item=".$key;
-
echo "var price=".$val;
-
}
-
echo "</script>";
-
is there any chance that would work?
gits 5,390
Expert Mod 4TB @Dormilich
wouldn't that be similar to: - echo 'var obj_name = '.json_encode($php_array);
-
kind regards
@freefony
nope, you’d end up redeclaring 2 variables
@gits: looks like that.
gits 5,390
Expert Mod 4TB
i did ... and i thought ... even when i'm not a php-expert that for the current case: - 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
Hey the jason function is a powerful tool! but little problem tho i still cant get the javascript array. -
//these two lines works perfectly
-
$mylist=jason_encode($list);
-
var_dump($mylist);
-
//output: string(64) "{"coke":"70","Emzor Paracetamol BP":"2","Paracetamol BP":"5000"}"
but the following codes return nothing what am i doing wrong? -
echo "<script languege='javascript'>";
-
echo "var mylist=".json_encode($list);
-
echo "document.write(mylist)";
-
echo "var data=eval(mylist)";
-
echo "</script>";
-
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
-
<script type="text/javascript">
-
var a = new Array('<?php echo implode("','",$php_array); ?>');
-
</script>
-
That should do the trick.
@didoamylee
it doesn't. because the PHP array is associative and javascript arrays are always numeric.
Ok guys! i got working -
<?php
-
$qry="select * from stock";
-
$rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
-
while($row=mysql_fetch_assoc($rst)){
-
$item=$row['item'];
-
$list[$item]=$row['price'];
-
}
-
?>
-
<script type="text/javascript" language="javascript">
-
var list=new Array('<?php echo json_encode($list); ?>');
-
document.write(list);
-
-
</script>
-
this suits my purpose and would solve a lot of problems i ve been facing with jscript and php arrays thanks to u guys
but you know that you sacrifice your PHP array keys with this?
how to do print_r() in Javascript - var my_php_array = { //… } // from json_encode()
-
my_php_array.toString = function()
-
{
-
var str = "";
-
for (var key in this)
-
{
-
str += key+" => "+this[key]+"\n";
-
}
-
return str;
-
}
- div.innerHTML = my_php_array;
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?
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Sandman |
last post by:
Hello
I have been trying to wrap my head arouns this, but I can't seem to get it to
work the way I want it to. Could someone helpful please tell me how I get this:
<function>...
|
by: Sven Neuberg |
last post by:
Hi,
I have been handed the task of updating and maintaining a web
application, written in ASP and Javascript, that takes complex
user inputs in HTML form and submits them to server-side ASP...
|
by: ralphNOSPAM |
last post by:
Is there a function or otherwise some way to pull out the target text
within an XML tag?
For example, in the XML tag below, I want to pull out 'CALIFORNIA'.
...
|
by: Marc van Boven |
last post by:
I'm stuck with the following problem:
My nusoap-client calls a server-function giveCombination(). The
function giveCombination should return something like
array(
=> array(
'a_id' => 6,...
|
by: djdave |
last post by:
My problem is that i need an algorithm parse parse HTML.
For an HTML page, my script has to parse all tags to get all forms
values, even if there is frame, iframe, ...
How can i do such a script ?...
|
by: Paulers |
last post by:
Hello,
I have a log file that contains many multi-line messages. What is the
best approach to take for extracting data out of each message and
populating object properties to be stored in an...
|
by: Aaron |
last post by:
I'm trying to parse a table on a webpage to pull down some data I
need. The page is based off of information entered into a form. when
you submit the data from the form it displays a...
|
by: Jasper |
last post by:
Hi, Maybe this is off-topic, but perhaps you can help. I'm looking for ideas
on how to parse a data file.
I dont know XML but I know it parses data in text format.
I have a structured data...
|
by: Philip Semanchuk |
last post by:
On Oct 12, 2008, at 5:25 AM, S.Selvam Siva wrote:
Selvam,
You can try to find them yourself using string parsing, but that's
difficult. The closer you want to get to "perfect" at finding URLs...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |