AS#3 organize variables loaded from PhP - php

I am having a problem of how to organize my variables in flash that are from a PHP script.Ideally i want them in an array type format so i can loop through them.Below is some code to go with.
function completeHandler(evt:Event){ // after loading the php
var symbolsArray:Array = new Array()
symbolsArray.push(evt.target.data.symbol_1);// php variable named: symbol_1, symbol_2
trace(evt.target.data);
}
The above is allworking, the PHP variables are listed as symbol_1, symbol_2 etc
Instead of pushing each variable separably into the array i want a loop, along the lines of:
function completeHandler(evt:Event){
var symbolsArray:Array = new Array()
var counter =1
symbolsArray.push(evt.target.data.symbol_+counter); this is the issue
trace(symbolsArray[0]); //returns NaN
}
Below is the php return vars to flash to give an idea:
$returnVars['symbol_1'] = $virtualReel1[0];
$returnVars['symbol_2'] = $virtualReel1[1];
$returnVars['symbol_3'] = $virtualReel1[2];
$returnVars['symbol_4'] = $virtualReel2[0];
$returnVars['symbol_5'] = $virtualReel2[1];
//etc
$returnString = http_build_query($returnVars);
echo $returnString;

symbolsArray.push(evt.target.data["symbol_"+counter]);
If you need to dynamically query properties of an object, you address it as an Array or a Dictionary, by a string key, which can be dynamically formed. Works on anything.

The returned data can be treated as an Object (containing Objects) so you can loop thru it like so:
function completeHandler(evt:Event)
{
var symbolsArray:Array = new Array();
for each (var obj:Object in evt.target.data)
{
symbolsArray.push(obj);
}
}
If you know all items are oif same type, you can cast the object. eg: if all Numbers:
symbolsArray.push(Number(obj));
Or Strings:
symbolsArray.push(String(obj));

Related

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

How to create a blank associative array in php

My php script returns data to the web client where it is processed by javaScript.
If data is found it is stored in an associative array / object. If no data is found I would like to send a blank associative array.
The only example I have seen on line is in the manual where you create an empty class and then instantiate an object from that.
Below is my code and the results it produces on the web client side
$sql = 'select job, client, project from jobs j left join client c on c.key = j.cKey where j.key='.$this->p['reckey'];
if ( $result = $db->query($sql) )
{
if ($result->num_rows > 0)
{
$l = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
$this->res_array['info'] = $l[0];
}else{
$this->errors[] = 'No such job # '.$this->p['reckey'];
$this->res_array['info']=[];
}
}else{
$this->errors[] = 'Query failed!';
$this->res_array['info']=[];
}
$this->res_array['errors'] = $this->errors;
echo json_encode ($this->res_array);
Here are two examples of what the data looks like when it arrives at the web client before it is decoded by JSON. Note the difference in the "info" element.
response {"info":{"job":"999","client":"My Company, Inc. ","project":"This Project"},"errors":[]}
error response {"info":[ ],"errors":["No such job # 0"]}
In the successful response I have an object/associative array where I would use the
for (variable in object) {...}
In the blank response I just get the standard array [ ] square brackets where I would use the
for (step = 0; step < info.length; step++) {}
This occurs of course because I am specifying a blank array in the php code above.
My question is simple how can I change my php code so a blank associtive array is transmitted?
The only example I have seen on line is in the manual where you create an empty class and then instantiate an object from that.
Sounds like you've answered your own question!
Since in JavaScript an object and an associative array are basically the same thing all you have to do is replace this line:
$this->res_array['info']=[];
With this one:
$this->res_array["info"] = new StdClass;
Or if you want to make the change only before sending the response you could check for an empty info array and replace it with an empty class.
if(!count($this->res_array["info"]))
$this->res_array["info"] = new StdClass;
I would suggest to take the best of both worlds, and let PHP generate an array of associative arrays, even though you expect at the most one, but at least you'd use the same structure for when you have none.
So change:
$this->res_array['info'] = $l[0];
to:
$this->res_array['info'] = $l;
And then in JavaScript do:
for (var step = 0; step < info.length; step++) {
for (variable in info[step]) {
// ...
}
}
... and if you still need to, you can deal with the no-data condition separately in JavaScript. Something like:
if (errors.length) {
// deal with this case...
}

Can't parse XMLHttpRequest.response to Object or Array

I'm trying to refresh the content of my cells of an table. Therefore, I have a JavaScript which contains an AJAX request to a .php file, which creates my content that I want to insert into my table via JavaScript. The .php files last command is something like echo json_encode($result);.
Back in the JavaScript it says:
var testarray = xmlhttp.response;
alert(testarray);
But the outut from the alert looks like:
{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}...
So it seems the variable testarray isn't handled as an array but as a string. I already tried var testarray = JSON.parse(xmlhttp.response), but this doesn’t work. Neither does eval() works.
I don't know what to do, so the response of my request becomes an object.
There are 2 strange things in your json:
this part is not json valid: ...}{...
two object should be separated by comas
The notation is object with string indexes not array with int indexes
it should be something like: [[1,2,3,4],[5,6,7,8]]
for the point 1. it looks like you have a loop that concatenate many json
for the point 2. the object notation can be used as an array so it doesn't matter
Some code:
//the folowing code doesn't work: }{ is not parsable
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
//the folowing code work and the object can be used as an array
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
alert(JSON.stringify(a[1]));
//the folowing code displays the real notation of a javascript array:
alert(JSON.stringify([1,2,3,4]));
I think that the problem here might be that your arrays do not have index 0.
e.g. if you output this from the server - it would produce an object:
$result = [];
for ($i = 1; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // outputs an object
if you output this from the server - it would produce an array:
$result = [];
for ($i = 0; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // produces an array
Anyways, even if your server outputs array as object - you should still be able to access it normally in javascript:
var resp = xmlhttp.responseText, // "responseText" - if you're using native js XHR
arr = JSON.parse(resp); // should give you an object
console.log(arr[1]); // should give you the first element of that object

Convert JSON to multidimensional JavaScript array

I receive from the server a JSON like the following:
{"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"}
The developer who coded this used JSON_FORCE_OBJECT as a parameter of the json_encode method in PHP.
In JavaScript is there any "magics" (that is, not a custom function) to convert this structure to a multidimensional array?
I would want something like:
[["image1.jpg","texthere","2"],["image66.jpg","texthere","1"]]...
Disclaimers:
- I'm looking for a native implementation (not JQuery);
- The PHP can be eventually changed (if needed);
Any help is appreciated, thanks in advance.
The easiest way I can think of to do what you want is to use regular expressions to convert the JSON from object literals to array literals.
Unfortunately, Simon Cowell is more magical than this approach.
//I don't know why you don't want a custom function.
function dataToArray(data)
{
data = data.replace(/"[0-9]+":/g,""); //Remove all index keys
data = data.replace(/,"length":"[0-9]+"/g,""); //Remove length key-value pair
data = data.replace(/{/g,"["); //Change the left brackets
data = data.replace(/}/g,"]"); //Change the right brackets
return JSON.parse(data);
}
Not magic, but you can loop over the data and test what type of value it has.
A basic example would be as follows. It doesn't have the error checking I'd want in production code though.
var data = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function data_to_array(data) {
var array = [];
for (var key in data) {
var value = data[key];
if (typeof value === 'string') {
array[key] = value;
} else {
array[key] = data_to_array(value);
}
}
return array;
}
var array = data_to_array(data);
console.log(array);
Make sure you add hasOwnProperty checks if your object prototypes might be messed with. You should probably also add a check to make sure that only integer keys are added to the array.
There is no built-in functions. If you have JSON string, you can do string replacement, otherwise you have to loop as shown below.
var dataObject = {"0":{"0":"image1.jpg","1":"texthere","2":"0"},"1":{"0":"image66.jpg","1":"texthere","2":"1"},"2":{"0":"image12.jpg","1":"texthere","2":"2"},"3":{"0":"image44.jpg","1":"texthere","2":"3"},"4":{"0":"image34.jpg","1":"texthere","2":"4"},"5":{"0":"image33.jpg","1":"texthere","2":"5"},"6":{"0":"image21.jpg","1":"texthere","2":"6"},"7":{"0":"image32.jpg","1":"texthere","2":"7"},"8":{"0":"image13.jpg","1":"texthere","2":"8"},"9":{"0":"image11.jpg","1":"texthere","2":"9"},"10":{"0":"image03.jpg","1":"texthere","2":"10"},"length":"12"};
function getArray(object){
var array = [];
for(var key in object){
var item = object[key];
array[parseInt(key)] = (typeof(item) == "object")?getArray(item):item;
}
return array;
}
var dataArray = getArray(dataObject);

how do i dynamically create a multidimensional javascript array

I'm trying to dynamically build a javascript array where _tags is a globally defined array and then send it to php via ajax request. Basically I need the uid as a key and x,y as a sub array. in php it would look something like
$arr[$uid] = array('x'=>$x,'y'=>$y);
but im having trouble figuring out an array like this in javascript, heres what i have
function add_tag_queue(uid,x,y){
var arr = new Array(3);
arr[0] = uid;
arr[1] = x;
arr[2] = y;
_tags.push(arr);
}
This works ok as long as their is only
one entry being added to the array,
I'm adding multiple values, in other
words the function will run a few
times and then i want to send that
entire array, but this seems to just
be adding everything with a comma
delimeter.
Im not sure what youre saying exactly here. The second example i previously gave assumes there is a single x,y pair for each uid but places no limits on how many uids are in _tags. Thats why var _tags = {}; is ourside of the function - so its a global variable.
The following modifications would allow you to have multiple x,y pairs for each uid:
function add_tag_queue(uid,x,y){
/*
* detect if _tags[uid] already exists with one or more values
* we assume if its not undefined then the value is an array...
* this is similar to doing isset($_tags[$uid]) in php
*/
if(typeof _tags[uid] == 'undefined'){
/*
* use an array literal by enclosing the value in [],
* this makes _tags[uid] and array with eah element of
* that array being a hash with an x and y value
*/
_tags[uid] = [{'x':x,'y':y}];
} else {
// if _tags[uid] is already defined push the new x,y onto it
_tags[uid].push({'x':x, 'y':y});
}
}
This should work:
function add_tag_queue(uid,x,y){
_tags.push([uid, x,y]);
}
if you want the uid as the key then you need to use an object/hash not an array
var _tags = {}; // tags is an object
function add_tag_queue(uid,x,y){
_tags[uid] = {'x':x,'y':y};
}
You could always just build it in php and json_encode it.
You're looking to implement an associative array in Javascript. While Javascript does not support associative arrays, Javascript objects can be treated much the same.
Try this instead:
_tags = {}
function add_tag_queue(uid,x,y){
_tags[uid] = {x:x, y:y};
}
_tags is now an object and you'll be adding a new object at the uid key. Likewise, the x,y pair is stored in an object. The first x is the key and the second is the value. To clarify, you could write it like this:
function add_tag_queue(uid,xValue,yValue){
_tags[uid] = {x:xValue, y:yValue};
}
It looks very similar to the PHP example you gave:
function add_tag_queue(uid,x,y){
_tags[uid] = {x: x, y: y};
}
This is how I create multidimensional arrays in JS. I hope this helps.
var arr= [];
arr[uid] = new Array();
arr[uid]["x"] = xvalue;
arr[uid]["y"] = yvalue;

Categories