Iterating over PHP array to create Javascript array with PHP foreach - php

I'm having a bit of trouble with an annoying ',' during the iteration of a PHP array to produce a Javascript array. Essentially, what I have is this:
<?php
$array = array(StdObject,StdObject,StdObject);
?>
//later that page...in JavaScript
var list = [
<?php foreach($array as $value):?>
'<?=$value->some_letter_field?>',
<?endforeach;?>
];
Unfortunatly, what this code does is produce output that looks like this:
var list = ['a','b','c',];
Notice that extra comma in the JavaScript array? This is causing some issues. How would I go about re-writing this PHP snippet so that extra comma doesn't get printed, producing a properly formatted JavaScript array?
The expected output should be:
var list = ['a','b','c'];
I appreciate your help in advance.

You don't need to do this yourself, PHP has a function called json_encode that does what you want. If for some reason you don't have PHP 5.2.0, there are a lot of implementations in the comments of that page to get around that.

Use implode() to glue up array elements. It will take care about commas
//later that page..in JavaScript
var list = ['<?=implode("', '", $array)?>'];

You can use this to generate the json array:
$list = json_encode($array);
And then read it in Javascript:
var list = <?=$list?>

This will do the trick:
<?php
$filtered = array();
foreach($array as $value) {
$filtered[] = $value->some_letter_field;
}
echo 'var list = ' . json_encode($filtered);
?>

How about converting array to a valid JSON object?
var list = JSON.parse("<?php echo json_encode($array); ?>");
Anyway, do you really need to generate JS code on the fly? Isn't there another way to complete your task? JS generation is often considered a hack, and it can be avoided easily in many cases.

If you insist in keeping your current code for whatever reason, just:
var list = [
<?php foreach($array as $value): ?>
$output[] = "'".$value->some_letter_field."'";
<?php endforeach; ?>
echo implode(',', $output);
];

Related

Converting XML file elements into a PHP array

I'm trying to convert a Steam group members list XML file into an array by using Php.
The XML file is: http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml
The elements are the member's steam IDs, such as 76561198000264284
How can I go about doing this?
Edit: So far I've used something like this:
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
It outputs the first few elements, not ones specifically
from
This should return the fully accessible array:
$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);
You can now access items like this:
echo $arr->groupID64;
echo $arr->members->steamID64;
Edit:
To parse the streamID, you can do a for loop
$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}
you can use below functional code to get your correct answer
<?php
$getfile = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($getfile);
foreach($arr->members->steamID64 as $a => $b) {
echo "<br>".$a,'="',$b,"\"\n";
}
?>
OUTPUT
steamID64="76561198009904532"
steamID64="76561198004808757"
steamID64="76561198000264284"
steamID64="76561198016710420"
steamID64="76561198005429187"
steamID64="76561198030184436"
steamID64="76561197980763372"
steamID64="76561197972363016"
steamID64="76561198045469666"
steamID64="76561198010892015"
steamID64="76561198028438913"
steamID64="76561197967117636"
steamID64="76561197980283206"
steamID64="76561197992198727"
steamID64="76561198018960482"
steamID64="76561198071675315"
steamID64="76561198010447988"
steamID64="76561198025628761"
if you wish to customize you can make it as per your need. let me know if i can help you more..

Creating an array of clients

For my select boxes switching, I need to pre-build a javascript array for the select option values by using php to generate a js array on load. I have done this until now by creating an object and adding it to an array, but now I need one of the object's properties to be an array of years. I'm close (the object's clientForm property will return a csv list if I document.write it), but I don't think it's an array as I can't access the length property and the previous document.write doesn't output array. Can anyone spot what I am doing wrong or suggest an alternative method?
Here is the php which outputs the Javascript array (I've built the system in CodeIgniter):
echo '<script type="text/javascript">';
$array = 'var companies = new Array();';
$i = 0;foreach($clientList as $client) :
$array .= 'arrayItem'.$i.' = {clientNo:"'.$client->client_id.'", clientCompany:"'.$client->client_company_name.'", clientRef:"'.$client->client_ref_no.'", clientForms: Array(';
if($client->client_forms != "")
{
$a = 0; foreach($client->client_forms as $form) :
$array .= $form.", ";
++$a; endforeach;
}
$array = substr($array, 0, -2);
$array .= ')};';
$array .= 'companies['.$i.'] = arrayItem'.$i.'; ';
++$i; endforeach;
echo $array;
echo '</script>';
And here is the current output:
<script type="text/javascript">
var companies = new Array();
arrayItem0 = {clientNo:"1", clientCompany:"Test1", clientRef:"UG123HS", clientForms: Array(1, 15)};
companies[0] = arrayItem0;
arrayItem1 = {clientNo:"2", clientCompany:"Test2", clientRef:"UF321HS", clientForms: Array(17)};
companies[1] = arrayItem1;
</script>
If you want a look, here is the full outputted code on jsfiddle (jsfiddle can't seem to make my onclicks work, but they do on the actual webpage).
Thanks!
To create an array, you're better of using this syntax: clientForms: [1,15]
Or else don't forget to add new: clientForms: new Array(1,15)
You're code doesn't look too far off, since jsFiddle isn't working too well, it's hard to tell. I did notice one thing however.
Where you have list.options[i+1]=new Option(companies[i].clientCompany, companies[i].clientRef, false, false); //Add the first option in you should probably have list.options[cnt+1]=new Option(companies[i].clientCompany, companies[i].clientRef, false, false); //Add the first option in
Notice I changed the first i to cnt. i is the counter for stepping through the array and cnt is actually your option counter. You could have very potentially been leaving blank options if your actual page didn't produce results with every array item.
EDIT:
This was in the function replaceCompanySelect.
Thanks to #mashington and #ParthThakkar for the answer, I wasn't aware of how json_encode() in PHP and JSON.parse() in javascript could work together. here is my new php code:
echo '<script type="text/javascript">';
echo "var companies = JSON.parse('".json_encode($clientList)."');";
echo '</script>';

Php javascript conflict with passing javascript to php

I have a slight problem. I have several arrays in php with different team names. Each array contains teams of a certain league. When I click an add button I get the option to add a new entry to the calendar. I want the drop down to have only the teams for that league. onclick of the add button I call a javascript function that knows what division was clicked. However in order to give the javascript the information for which teams to display I have to pass it one of the php arrays. The problem I am having is telling php which array to pass to javascript depending on which league javascript is on. I don't want to specify the array myself because there is an option to add a league and this would mean having to code in more code each time a league is added. The point of the site is being dynamic.
here is some code.
for ($i = 0;$i<$sizeof($leaguesarray);$i++){
$htmlimploded[$i] = implode($html[$i]);
}
here I have used emplode to make all of my php arrays readable into javascript.
for (var h = 0; h<size; h++){ // goes through every league
if(h == leaguenum){ // finds the league for the clicked add button
// this is the line that I have trouble with I can't think of
//anyway of telling it which array to use since it is serverside code.
var myarray = ["<? echo $htmlimploded[]?>"];
}
}
Javascript code above.
Imploding works but why not json_encode($array)? It's a simpler, built in way to turn php arrays into javascript objects or arrays. If you have something like:
$league1 = array('team1', 'team2');
$league2 = array('team3, 'team4') ;
Then make a multidimensional associative array of these:
$all_teams = array('league1'=>$league1, 'league2'=>$league2);
encode it into a Javascript object and print it into your JS:
$encoded = json_encode($all_teams);
print 'var teamObject = '.$encoded.';';
If you were to console.log(teamObject) you'd see something like this:
{"league1": ["team1", "team2"], "league2": ["team3", "team4"]}
Looks complicated, but now you can pull out the array you desire very easily. The league 1 array is teamObject.league1 and the league2 array is teamObject.league2, and so on.
i think you missed something in the following code:
var myarray = ["<? echo $htmlimploded[]?>"];
By right, it should be:
var myarray = ["<?php echo $htmlimploded[]?>"];
Assuming that PHP knows the names of the leagues and the teams and that JavaScript knows the league name that is clicked, You can wrap the arrays of the team names inside an object with the league as the name of the property.
<?php
$arr = array("League1" => array("Team 1", "Team 2"),
"League2" => array("Team 3", "Team 4")
);
?>
var obj = {};
<?php foreach ($arr as $k => $v): ?>
obj.<?php echo $k; ?> = ["<?php echo implode('","', $v); ?>"];
<?php endforeach; ?>
Then when a user selects a league, you can loop through the array of the property (which is the league name) of the object.
clickedLeague = "League1";
for (var i = 0; i < obj[clickedLeague].length; i++)
{
console.log(obj[clickedLeague][i]); // Logs the team name to console
}

assigning multidimensional php array to javascript array

I know this may be a duplicate, but I cant wrap my brain around the other examples. Help would be appreciated.
I have a php array that i need to assign to a javascript array. Here is my amateur way of doing it now.
You can see source at http://www.preferweb.com/accentps/index.php
<?php
$i=0;
while ($result1 = mysql_fetch_array($query1)){
print "<script>";
print "var size[".$i."]=" .$result1['type'].";\n";
print "var 25[".$i."]=" .$result1['25'].";\n";
print "var 50[".$i."]=" .$result1['50'].";\n";
print "var 100[".$i."]=" .$result1['100'].";\n";
print "var 250[".$i."]=" .$result1['250'].";\n";
print "var 500[".$i."]=" .$result1['500'].";\n";
print "var plus[".$i."]=" .$result1['plus'].";\n";
$i = $i+1;
}
print "var tick='1';\n";
print "alert (tick);\n";
print "</script>\n";
?>
<script>
alert (500[0]);
</script>
This alerts undefined for the tick alert and nothing for the second alert.. Thanks..
You cannot use an integer as a variable name, like in this line: print "var 25[".$i."]=" .$result1['25'].";\n";. 25 cannot be a variable.
If you want to map an array to a javascript object, you might want to take a look at json_encode
EXAMPLE
Your code could be written like this:
<?php
$result = array();
while ($row = mysql_fetch_array($query1)){
$result[] = $row;
}
?>
<script>
var result = <?= json_encode($result); ?>;
alert (result[1][500]);
</script>
looks much cleaner to me.
The way you are working with arrays is not correct.
First you should initialize the array:
var myArr = [];
Then if you just want to add to the array, you can use push:
myArr.push("something");
or to a specific index:
myArr[11] = "something";
The syntax you are using is completely invalid.
Your code is wrong because of what is generated by PHP (especially because you use numbers as variable names in JavaScript, plus you define the same variables with each loop).
To simplify what you want to achieve, just create some variable in PHP and assign a value to it. Lets call it eg. $my_proxy_var.
Then pass it to JavaScript like that (within some <script> tag):
var myProxyVar = <?php echo json_encode($my_proxy_var); ?>;
Just remember that:
non-associative array in PHP becomes simple array in JavaScript,
associative array in PHP becomes object in JavaScript,
This is important so you can avoid confusion and chose between non-associative and associative array on each level.
You can test the code on this codepad.
You can't use numbers as variable names in javascript.
You don't need to use "var" with each line. Something like
var test = [];
test[1] = 'some value';
test[2] = 'some value';
You probably want to look at using the JSON_ENCODE function from PHP
<?php
if (!func_exists('json_encode')) die('sorry... I tried');
$buffer = array();
while ($value = mysql_fetch_assoc($result)) {
$buffer[] = $value;
}
echo "<script>var data = ".json_encode($buffer)."</script>";
?>
<script>
console.log(data);
</script>
Requires PHP 5.2.0

Multiple Variable Variables in PHP

I am fairly new to PHP and programming in general... I am attempting to use a foreach loop to set some options on a page I have created. It all works except for the last section, where I am attempting to assign variables dynamically, so I can use them outside the loop.
<?PHP
$array=array(foo, bar, baz);
foreach ($array as $option) {
// I have if statements to determine what $option_req
// and $option_status end up being, they work correctly.
$option_req="Hello";
$option_status="World";
$rh='Req_';
$sh='Status_';
$$rh.$$option=$option_req;
$$sh.$$option=$option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
?>
When the loop is finished, should this now give me six variables?
$Req_foo
$Status_foo
$Req_bar
$Status_bar
$Req_baz
$Status_baz
I have played with this a bit, searches on Google seem fruitless today.
To access some array item, just access some array item.
No loops required.
$req = array("foo" => 1,
"bar" => 2,
"baz" => 3,
);
echo $req['foo'];
plain and simple
Looks like PHP doesn't like the concatenation when you're trying to do an assignment. Try doing so beforehand, like so:
<?php
$array = array('foo', 'bar', 'baz');
foreach ($array as $option)
{
$option_req="Hello";
$option_status="World";
$rh = 'Req_';
$sh = 'Status_';
$r_opt = $rh.$option;
$s_opt = $sh.$option;
$$r_opt = $option_req;
$$s_opt = $option_status;
}
echo "<br>R_Foo: ".$Req_foo;
echo "<br>S_Foo: ".$Status_foo;
echo "<br>R_Bar: ".$Req_bar;
echo "<br>S_Bar: ".$Status_bar;
echo "<br>R_Baz: ".$Req_baz;
echo "<br>S_Baz: ".$Status_baz;
As other commenters suggested, this isn't a great practice. Try storing your data in an array, rather than just cluttering up your namespace with variables.
You could (though you should not!) do:
${$rh.$option} = ...
Variable variables don't work that way. You need to have one variable containing the string.
$opt_r = $rh.$option;
$$opt_r = $option_req;
$opt_s = $sh.$option;
$$opt_s = $option_status;
Also, make sure to quote your strings:
$array=array('foo', 'bar', 'baz');
I don't suggest using variable variables, but if you want to, this is how to do it.

Categories