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
}
Related
I'm attempting to make 1 array out of 2 existing arrays (which cannot be modified). In order to do this I'm creating the array in a foreach which is nested in another foreach.
The code I used:
$language_option = array();
foreach(Languages::getFullSelectOptionsList() as $country_description_1 => $country_code){
foreach(Languages::getFullSelectOptionsList(TRUE) as $country_description_2 => $country_code){
$language_option[$country_code] = $country_description_1.' - '.$country_description_2;
}
}
In this code "Languages::getFullSelectOptionsList()" returns an array with the 1st country descriptions.
And "Languages::getFullSelectOptionsList(TRUE)" returns an array with the 2nd country descriptions.
This is what my code does:
dropdown results
But what I'd like it to do is:
dropdown wished results
As you can see in the first picture only the last array value of "country_description_1" is used instead of using them all.
Are there any errors in my code, is this not possible to do or is there an easier way of doing this?
Thanks.
Here you can get reference of this code.
But This will not work because you need to specify the values where $first_array[$i]
$language_option = array();
$first_array = Languages::getFullSelectOptionsList();
$second_array = Languages::getFullSelectOptionsList(TRUE);
for($i=0;$i<count($first_array); $i++){
$language_option[$country_code] = $first_array[$i].' - '.$second_array[$i];
}
Instead of $first_array[$i].' - '.$second_array[$i] put code according to your array structure to get description or code (key value).
I have 3 arrays created in the following way:
$start=2013 ;
$end=2015;
$no_of_bars=$to-$from+1;
$xdata=array();
for($year=$start;$year<=$end;$year++){
${"y".$year}=array();
$i=0;
$query=mysql_query("SELECT tld_master.location,tld_dose.year, AVG(tld_dose.dose)*4 as avgdose from tld_master left join tld_dose on tld_master.tldno=tld_dose.tldno where tld_master.site='F' and tld_dose.year=$year GROUP BY tld_dose.year, tld_dose.tldno");
while($result=mysql_fetch_array($query)){
$xdata[$i]=$result['location'];
${"y".$year}[$i]=$result['avgdose'];
$i++;
}
}
It creates three arrays y2013,y2014,y2015.
I have to pass this array to jpgrpah to plot a groupbar. New Bra objects are created in this way
$j=0;
for($year=$start;$year<=$end;$year++, $j++){
${"plot".$year}=new BarPlot(${"y".$year});
${"plot".$year}->SetFillColor($color_array[$j]);
if($year!=$end){$sep=",";}else{$sep="";}
$plots.="$"."plot".$year.$sep;
}
There are three bar plots plot2013,plot2014,plot2015. All these three are arrays. I want to pass these arrays to jpgraph function given below:
$gbplot = new GroupBarPlot($plots);
but this is not working. But if I am changing it to the one given below, it works
$gbplot = new GroupBarPlot(array($plot2013,$plot2014, $plot2015));
I think that in the second one arrays are passed as arguments where as in first one just array name is passed as string. How can I pass the array created inside the for loop to the jpgraph function?
Not tested, but try the code below.
$j=0;
for($year=$start;$year<=$end;$year++, $j++){
${"plot".$year}=new BarPlot(${"y".$year});
${"plot".$year}->SetFillColor($color_array[$j]);
$plots[] = ${"plot".$year};
}
$gbplot = new GroupBarPlot($plots);
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>';
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
I know how to send data via a multi-select form object and group the data into an array:
<select name="my_data[]" multiple="multiple"/>
Is it possible to have multiple different select boxes with "single" values and push them all into an array? i.e.
<select id="select-1" name="my_data[]"/>
<select id="select-2" name="my_data[]"/>
result would be
[
0 => {value of select-1},
1 => {value of select-2}
]
What would be a good way to combine the data from the selects into an array if not possible?
Ah, just removing multiple seems to work. Zend Framework's FormSelect helper automatically added it when you have "[]" in your form element name and I did not realize that.
This assume you're getting all <select>'s on the page:
// get all selects
var boxes = document.getElementsByTagName("select"),
arr = []; // your final values array
// for each select, pull out the value and push it into 'arr'
for(var i = 0, len = boxes.length; i < len, i++) {
arr.push(boxes[i].value);
}
While you probably can do it I wouldn't recommend it. Just because it isn't that clear from someone else reading the code.
A better approach is simply to combine them serverside. Assuming:
<select id="select-1" name="data_1[]"/>
...
<select id="select-2" name="data_2[]"/>
...
On the PHP side:
$data1 = $_POST['data_1'];
$data2 = $_POST['data_2'];
$combined = array_merge($data1, $data2);