Storing valuesin a javascript array - php

Hello people here is my code
function send(Eqt_Param,Eqt_Param_value)
{
var Eqt_Paramv=Eqt_Param+'='+Eqt_Param_value;
alert(Eqt_Paramv);
}
every time Eqt_Param and Eqt_Param_value will be different ...iam sending values onclick so run this script for 5 times well i get 5 different values overall.but now i need to save each value in an array so that i can use the array element in the script function again,
plzz help me to fix this

var data = new Array();
function add(param, value){
var temp = {'param' : param, 'value' : value};
if (data.length >= 50)
data.shift();
data.push(temp);
}
Call the function after the processing like
add(Eqt_Param,Eqt_Param_value);

Create a global array variable, and simply assign the function to it.
var array = [];
function send(param, param_value) {
array[] = Eqt_Param + '=' + Eqt_Param_value;
}
or
var array = [];
array[] = send(param, param_value);
function send(param, param_value) {
return Eqt_Param + '=' + Eqt_Param_value;
}
The array will contain all the results anytime the function is run.
Hope this helps.

not sure if this is what u want... but u can try this out..
create a global array...
var globalArray=[];
use push() to push the values u want in the array
function send(Eqt_Param,Eqt_Param_value)
{
var Eqt_Paramv=Eqt_Param+'='+Eqt_Param_value;
alert(Eqt_Paramv);
globalArray.push(Eqt_Paramv); // i am pushing the result(Eqt_Paramv) here,
}

Related

A Simple Random Generator

How can I create a generator where when a button is pressed it selects a random word that I've added to a list.
For example, "Apple", "Banana" and "Pear" are on my list and I want the end user to press a button and the code will fetch one of the fruits but completely randomly, how can I do this?
Regards,
John
First, you mention a list; this directly translates to an array.
Second, you have a finite number of options, presented in the array, and you want to pick one at random. This translates to picking an index (integer) at random. Since arrays start at 0 and you cannot choose an item passed the last index, you will then need to choose a random range between 0 and the length of the array.
If you simply want to get a random item from a list from pressing a button, you'll most certainly want to isolate this to the front-end, i.e. javascript:
var randomWords = [
'Apple',
'Banana',
'Pear'
];
function getRandomWordFromList(list) {
var index = getRandomInt(0,list.length);
return randomWords[index];
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
document.getElementById('myButton').onclick = function() { // for example's sake...
document.getElementById('theOutput').innerHTML = getRandomWordFromList(randomWords);
};
(getRandomInt from Generating random whole numbers in JavaScript in a specific range?)
Also, if your array is fragmented (i.e. some indices are missing), you can use (safer, albeit more convoluted):
function arrayKeys(array) {
var i,keys = [];
for ( i in array ) {
if ( isInt(i) && array.hasOwnProperty(i) ) {
keys.push(i);
}
}
return keys;
}
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
function getRandomInt(min,max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRandomWordFromList(list) {
var keys = arrayKeys(list); // be sure to only get indices that exist
var key = getRandomInt(0,keys.length-1);
return list[keys[key]];
}
var randomWords = [
'Apple',
'Banana',
'Pear'
];
delete randomWords[1]; // remove 'Banana'
var theWord = getRandomWordFromList(randomWords);
If there is something server-side that influences the randomized list, you can populate the randomWords array via PHP as follows:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
?>
<script type="text/javascript">
var randomWords = [<?php echo "'".implode("','",$randomWords)."'"; ?>];
// don't forget your getRandomWord functions
</script>
Bonus: If the randomization must happen entirely server-side, i.e. php, here is a translation:
<?php
$randomWords = array(
'Apple',
'Banana',
'Pear'
);
echo $randomWords[array_rand($randomWords)]; // output somewhere
?>
A simple javascript closure to demonstrate.
var generateRandom = (function () {
var fruit;
return function () {
if (fruit === undefined) {
fruit = ["Apple", "Banana", "Pear"];
}
return fruit[Math.floor(Math.random() * fruit.length)];
}
}());
Here Math.random gives a number between 0 and 1. so I will be multiplying it with the array length to get a number between 0 and fruit.length. this would be the index of the item that we are going to pick.
Here's just a quick example of how to might do this. Actions (clicking in this case) are taken care of by JavaScript, so I highly recommend taking care of all of it there. The idea is that you don't need to have separate html or especially php worry about this when you could package it up in a JavaScript object. This code is far from perfect, but I think it's a good starting point for you. Notice that all you need to do to make this run is have this script included and simply type (in js) wordRandomizer.run(myElem); when myElem is a reference to an element that is in the dom (I just used the body in this example).
Demo here.
var wordRandomizer = { //the name of your "app"
run : function(targetElem) { //this is the function you will call to make it all happen
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup : function() {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function() {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem : function() {
var rand = this.getRandInt(1, this.items.length) - 1; // -1 because arrays start at 0
this.elem.innerText = this.items[rand];
},
getRandInt : function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items : [
'itemA',
'itemB',
'itemC',
'itemD'
]
};
wordRandomizer.run(document.body);
//here, you just pass in the element where your "app" will attach its output.
//If you want to get fancier, you could make more things optional, add more functionality, etc and pass in those options here.
Oh, and you should add some logic to make sure the item selected will not be the same item as before. There's several ways to do that easily, but I'll leave the fun to you :)
Using Javascript:
var fruit;
var rand = Math.random();
if (rand <= 0.33) {
fruit = 'Apple';
} else if (rand > 0.34 && rand <= 0.66) {
fruit = 'Banana';
} else if (rand > 0.67) {
fruit = 'Pear';
}
Math.random() will return a number between 0 and 1.

Saving Javascript Array to PHP

Hello i am quite new to javascipt so please explain things clearly. I am currently running a php page which includes:
upp.php
<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>
this items array contains objects which is saved like this:
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
$.post('upp.php',{ items: JSON.stringify(oldItems) }, function(response) {
window.location.href = "upp.php";
the result of the page appears like this:
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there anyway i can save this information into PHP and split the data so I can manipulate it one at a time like a loop or something. For example:
1st time:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
Next:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
etc.
Thanks.
upp.php:
<?php
$array = json_decode($_POST['items'], True);
foreach ($array as $key=>$line) {
# $key is a number like 1173627548
# and $Line is an array with methv, q1, q2, q3, q4, and comm
}
?>
That will show you the array it got from the JSON. Now you can work with the data.

javascript equivalent to php max for arrays

I have a function in php that selects the array with that contains the most elements.
$firstArray = array('firstArray','blah','blah','blah');
$secondArray = array('secondArray','blah','blah');
$thirdArray = array('thirdArray','blah','blah','blah','blah');
then I get the name of the variable with the highest length like this:
$highest = max($firstArray, $secondArray, $thirdArray)[0];
but I am developing an application and I want to avoid using php and I have tried javascript's Math.max() to achieve the same results but it doesn't work the same way unless I do
Math.max(firstArray.length, secondArray.length, thirdArray.length)
But this is useless since I need to know the name of the array that contains the most elements. Is there any other way to achieve this?
This function takes as input an array of arrays, and returns the largest one.
function largestArray(arrays){
var largest;
for(var i = 0; i < arrays.length; i++){
if(!largest || arrays[i].length > largest.length){
largest = arrays[i];
}
}
return largest;
}
We can test it out with your example:
firstArray = ['firstArray','blah','blah','blah'];
secondArray = ['secondArray','blah','blah'];
thirdArray = ['thirdArray','blah','blah','blah','blah'];
// should print the third array
console.log(largestArray([firstArray, secondArray, thirdArray]));
The following url has a max() equivalent. It supports more then just numbers just like in php:
js max equivalent of php
If you feel ok with including 3rd-party libs, maybe http://underscorejs.org/#max does what you want:
var aList = [firstArray, secondArray, thirdArray];
_.max(aList, function(each) { return each.length; });

Passing by reference in AS3

How do I pass values by reference inside a for each construct in AS3? Basically, I want something equivalent to the following code in PHP:
foreach ($array as &$v) {
$v = $v + 1;
}
This would allow me to change all elements of the collection $array through a single loop.
Pointers don't exist in AS3 so you need to use Array.forEach method that executes a function on each item in the array:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html?filter_coldfusion=9&filter_flex=3&filter_flashplayer=10&filter_air=1.5#forEach%28%29
A bit off-topic but more info about values and references in AS3 (for functions)
In ActionScript 3.0, all arguments are passed by reference because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
You can not do this they way you do it in PHP. The for each loop will yield a reference variable v you can use to get the value, but setting v=v+1 would not change the original array, but erase the reference and set a new value only to v. But you can still modify all array values in one loop:
For a simple Array:
var array1 : Array = [ "one", "two", "three" ];
for (var i : int = 0; i < array1.length; i++)
{
array1[i] = "number " + array1[i];
}
For an associative array (it's actually an Object in Flash), use for...in:
var array2 : Object = { one:"one", two:"two", three:"three" };
for (var s:String in array2) // s is the string value of the array key
{
array2[s] = "number " + array2[s];
}
I think the second one is what you are looking for.
EDIT: weltraumpirat was correct. My original example wasn't modifying the contents of the original array which is probably what the original poster wanted. Here's some updated examples:
Updated example using for each:
for each (var s:String in arr)
{
arr[arr.indexOf(s)] = "<Your value here>";
}
Updated example using a standard for loop:
for (var counter:int = 0; counter < arr.length; counter++)
{
arr[counter] = "<your value here>";
}
Original example [Incorrect]:
for each (var s:String in array)
{
s = <your value here>;
}

assigning value to array in javascript

in php you could do like this:
$key1 = 1;
$key2 = 1;
$array[$key1][$key2] = 'hi';
in javascript i tried with this:
key1 = 1;
key2 = 1;
var array = new Array();
array[key1][key2] = 'hi';
but it didnt work. how can i do the same thing in javascript?
Your problem is that you need to instantiate the inner array before assigning values in it
var key1 = 1;
var key2 = 1;
var array = [];
array[key1]=[];
array[key1][key2] = 'hi';
Or you could do it all in one:
var array=[['hi']]
Also, you should avoid assigning to specific indexes unless you're updating an existing element. The first example above will automaticly add an element
array[0]=undefined;
If you want to use specific keys, and not just indexes, you should use dictionaries or objects (dictionaries and objects are the same thing i javascript)
The key1 property of array is undefined at the time you are trying assign the property key2 to it. You need to actually indicate that array[key1] is an array before you start assigning values to it.
For example:
array[key1] = [];
array[key1][key2] = 'hi';
JavaScript is having a problem with the key1 and key2 dimensions of your array being undefined. To correct this problem, these are changes you could make:
var key1 = 1;
var key2 = 1;
// define "array" as an empty array:
var array = [];
// define "array[key1] as an empty array inside that array
// (your second dimension):
array[key1] = [];
array[key1][key2] = 'hi';
PHP does some magic -- you can simply supply 2 keys and PHP "knows what you mean" and will define the $key1 and $key2 dimensions without thinking about it. See: PHP: arrays: If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key.
JavaScript requires you to be more explicit about array creation.
You can find neat implementations. For example, here is a way, which is a function creating an array for the rows and then, creating an array for each column (could be anidated in the other way, but...)
var sDataArray=MultiDimensionalArray(7,2);
//alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
The thing is, you just can't work the arrays just like PHP ones. Must treat them the way they really are: an array of arrays (of arrays (of arrays (of arrays)...)).
Good luck.

Categories