Creating an array of clients - php

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>';

Related

Iterating over PHP array to create Javascript array with PHP foreach

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);
];

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

How to reference a item in an array numerically when it has been created as an associative array

I am using PHP 5.3.6
I have the following code below. Everything works fine except for the last line which attempts to to return a value based on the position in the array as opposed to the associative name. Can anyone explain why this takes place and how I can build the array so that I can reference an item either by the associative name or position number?
Thanks.
<?php
class myObject {
var $Property;
function myObject($property) {
$this->Property = $property;
}
}
$ListOfObjects['form_a'] = new myObject(1);
$ListOfObjects['form_b'] = new myObject(2);
$ListOfObjects['form_c'] = new myObject(3);
$ListOfObjects['form_d'] = new myObject(4);
echo "<pre>";
print_r($ListOfObjects);
echo "</pre>";
echo "<hr />";
foreach ($ListOfObjects as $key => $val) {
echo "<li>" . $ListOfObjects[$key]->Property . "</li>";
}
echo "<hr />";
echo "<li>" . $ListOfObjects['form_a']->Property . "</li>"; // Works ok.
//Edit: ------------------------------------------------------------
//Edit: Everything above is for context only
//Edit: I'm only interested in the line below and why it does not work
//Edit: ------------------------------------------------------------
echo "<li>" . $ListOfObjects[0]->Property . "</li>"; //Does not work.
?>
function value_from_index($a,$k){
return array_slice($a,$k,1);
}
If you just want the first/last element of an array, try end($array) for the last item without destroying it and reset($array) to get the first.
Don't use reset and end if you're looping through an array as Flambino notes, this indeed results in some unexpected behaviour.
For anything inbetween you'll need to use array_slice()
Not the nicest way of doing it, but effektive and readable:
$i = 0;
$last = count($ListOfObjects);
foreach($ListOfObjects as $obj) {
if($i == 0) {
//do something with first object
$obj->property;
else if ($i == ($last-1)) {
//do something with last object
$obj->property;
}
}
PHP arrays aren't like arrays you know from most other programming languages, they are more like ordered hash tables / ordered dictionaries - they allow for access by named index and retain order when new items are added. If you want to allow access with numeric indices to such an array you have to define it that way or use one of roundabout ways given in other answers.
In your case you can use a single line of code to allow access by index:
$ListOfObjects += array_values($ListOfObjects);
This will extend your array with the same one but with numeric indices. As objects are always passed by reference, you can access the same object by writing $ListOfObjects['form_b'] and $ListOfObjects[1].

php arrays creating dynamically giving incorrect values

I want to create a array with values:
3,2,1.... and I want to use array_push and a forloop.
I have written the following code is not working..
============
<?PHP
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$temp4=1;
$temp5=1;
$arraytemp=array();
for($i=0;$i<4;$i++)
{
$r="temp";
$dd=$r.$i;
array_push($arraytemp,$dd);
}
echo $arraytemp[3];
?>
can you please let me know what I am missing
This is how should you assign $dd
for($i=0;$i<4;$i++)
{
$dd=${"temp".$i};
array_push($arraytemp,$dd);
}
your $dd has the name of your var as a string. you want to use this for this technique:
array_push($arraytemp,$$dd);
Pay attention to the double $$ :)
What happens here is the following: the $dd gets replaced by the string it contains. so your call
array_push($arraytemp,$dd);
will do this:
array_push($arraytemp,'temp0');
But you want this:
array_push($arraytemp,$temp0);
so you need to show you want an acutal $var with that name, so you add the $. It's just the way the syntax works, neccessairy to distinguish between a normal string and a string that's supposed to be a variable
confusing what do you want to achieve here, do you want to:
create array with value: temp0, temp1, temp2 ...
for($i=0;$i<4;$i++){
array_push($array,"temp{$i}");
}
echo $array[3];
create array with value: 0, 1, 2, 3 ..
for($i=0;$i<4;$i++){
array_push($array,$i);
}
echo $array[3];
create array with value based on your defined variable above ($temp0, $temp1 ...)
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$array = array();
for($i=0;$i<4;$i++){
$val = "temp{$i}";
array_push($array,$$val);
}
echo $array[3];
Easiest way, going by what you're requesting, although you didn't specify how many numbers you wanted to add. so for loop won't work that way. you're best off with a while loop.
$foo = array();
$i = 1;
while (some end condition) {
array_push($foo, $i);
$i++;
}
print_r($foo);

Categories