AS3 equivalent of PHP key array - php

Hey all, title may be abit misleading but i didnt know the correct way to write it.
Basically, how can i do the AS3 equivalent of this php code:
return array('x' => 0, 'y' => 0);

The standard way of doing it is like this. The main thing to remember is that 'Object' in AS3 is almost equivalent to PHP's associative array's.
var obj:Object = {x:0, y:0};
trace(obj['x']); // like in PHP
trace(obj.x); // also valid
// AS3 version of foreach in PHP
for(var key:String in obj) {
trace(key +" = " + obj[key]);
}

private var map:Dictionary = new Dictionary();
map["x"] = 0;
map["y"] = 0;

You can do something like this
var myArray:Array = new Array({x:'0'},{y:'1'},{x:'2'});
or
var myArray:Array = new Array({x:'0',y:'1'},{a:'1',b:'2'});

Related

Using array_push to add elements to array

I have an array & I'd like to add data to the array using PHP. I can't add it directly.
How would I do this using array_push?
<script type="text/javascript">
var parks = [{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}]
</script>
You can try:
//if your JSON string on server side <--PHP-->
$park = json_decode([{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png"}],true);
$park['key'] = 'someValue';
$newJSON = json_encode($park);
// if your JSON string on client side <--JS-->
var parkObj = JSON.parse(park);
parkObj.key = 'someValue';
console.log(JSON.stringify(parkObj));
//[{"title":"Football Park","lat":"55.86234","lng":"-4.250635999999986","img":"icon.png","key" : "someValue"}]
I found http://www.php.net/manual/en/function.array-merge.php and feel this will do the job for me - thanks for your input.

not receiving JSON from php with getJSON

I am trying to pass an array to the browser using php and jquery but I the when I try to use the 'data' returned from php's encode_json, it comes up undefined. I'm just learning php, jquery, and json and so far haven't found very good documentation on alot of this stuff, especially json, even in the books I have. Thanks in advance!
Here is a stripped down version of the jquery I have
$(document).ready(function(){
var jsonResult;//I will want to be able to use the data in other functions
$.getJSON("json.php", function(data){
jsonResult = data;
var str;
var nuts = [203,204,205,207];
str = '<p>' + data[nuts[0]].NutraDesc + '</p>';
$('#stuff').html(str);
}
);
});
This is the php:
include_once 'databasePHP.php';
$json_tst = $db->query( "SELECT def.Nutr_No, NutrDesc, Nutr_Val, Units
FROM nutr_def as def JOIN nut_data as data ON def.Nutr_No = data.Nutr_No
WHERE data.NDB_No = 1001 LIMIT 0, 2");
$food = array();
while($row = $json_tst->fetch(PDO::FETCH_ASSOC))
{
$Nutr_No = $row['Nutr_No'];
$food[$Nutr_No][] = array(
'NutrDesc' => $row['NutrDesc'],
'Nutr_Val' => $row['Nutr_Val'],
'Units' => $row['Units']
);
};
echo json_encode($food);
?>
which returns this json which I checked on jsonlint.com and it said it was valid:
{"203":[{"NutrDesc":"Protein","Nutr_Val":"0.85","Units":"g"}],"204":[{"NutrDesc":"Total lipid (fat)","Nutr_Val":"81.11","Units":"g"}]}
It probably doesn't work because the numbers should be strings. Try to add quotes around the numbers in nuts, like this:
var nuts = ["203","204","205","207"];
The following probably works as well:
str = '<p>' + data[String(nuts[0])].NutraDesc + '</p>';
Also, have you tried adding console.log(data); to the getJSON function to make sure it receives the JSON?
EDIT:
Here is a working JSFiddle from your code:
http://jsfiddle.net/rKLqM/
Things that were wrong:
you weren't parsing the result as JSON (JSON.parse)
NutraDesc was spelled wrong
You didn't convert the numbers to strings
You needed to add [0] to the jsonResult because there's an extra array within it (see the [])
In Javascript object property can be accessed with obj["propName"]
So, change
var nuts = [203,204,205,207];
to
var nuts = ["203","204","205","207"];

explode new line in javascript

How do I convert the php code below into javascript? I google it and found something to do with st.replace(/,/g,"\n") but how to apply it to the variable? I have low knowledge about javascript and trying to learn it.
$items = explode("\n", $model);
The answer is:
items = model.split("\n")
No, you are searching for [String].split("\n") which returns an Array. The replace you found would be similiar to implode("\n", explode(",", $model)).
The basically equivalent code is:
var model = 'some string...';
var items = model.split('\n');
var yourArray = [];
var yourString = 'a,b,c,d,e';
yourArray = yourString.split(',');

Sending and receiving data

Not getting data back into flash from php that queries mysql data, think the problem is with my as3 code here?
The php works, the as3 posts to the php ok, its the returning of the variables to as3 that I am unsure about and seems to be the problem?
public static function MineData():void{
var myRequest:URLRequest = new URLRequest("login.php");
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
var myVariables:URLVariables = new URLVariables();
myVariables.School_name_test = String(PostToPHP3.Temp_flash_TI_School_name_test);
myRequest.method = URLRequestMethod.POST;
myRequest.data = myVariables;
function onLoaded(event:Event) {
var myURLVariables:URLVariables = new URLVariables(event.target.data);
DT_display_string_teacher_login_teacher_first_name = myURLVariables.mined_teacher_first_name;
Main.listeningFORPortalteacherlogin.tellMainPortalteacherlogin();
}
myLoader.addEventListener(Event.COMPLETE, onLoaded);
myLoader.load(myRequest);
}
Kindest regards
Within your PHP file, ensure you're only echoing back the values which should be returned to Flash. The format for this returned string is:
VarName=Value
With any further values appended to the same String using the & operator to separate them:
VarName=Value&VarName2=Value2
And so on. See the following example for how you might need to use it:
<?php
echo "mined_teacher_first_name=" . $FIRST_NAME_RETURNED_FROM_SQL;
?>
This example obviously doesn't include all the PHP to retrieve the data from the database but that's how you get the data back to Flash. If you have a very large amount of data, you can also output an XML file from PHP and then parse that from within Flash.
I'll also add that your Flash code for extracting these values looks perfectly fine, although it's not absolutely necessary to convert them to a URLVariables object, you can in fact, access them directly from event.data if you so choose:
function onLoaded(event:Event) {
DT_display_string_teacher_login_teacher_first_name = event.target.data.mined_teacher_first_name;
Main.listeningFORPortalteacherlogin.tellMainPortalteacherlogin();
}

How to retrieve query string parameter and values using javascript (Jquery)?

Click me
$('.clickme').click(function(event) {
event.preventDefault();
var stringId = $(this).attr("id");
var mId = stringId.substring(2)
....
I can retrieve the value of id using ID of anchor element. I think I should be able to get it directly from href. So how do I retrieve value of id and status from HREF (url query string)?
I am using Jquery.
Thank you for your help.
UPDATE:
Also how do I can get all of the URL value .. i.e. "test.php?id=100&blah=blah"?
This code:
function querySt(ji) {
hu = $(".clickme").attr("href");
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
To use it:
document.write(querySt("id"));
document.write(querySt("status"));
Answer to your 'update':
http://ilovethecode.com/Javascript/Javascript-Tutorials-How_To-Easy/Get_Query_String_Using_Javascript.shtml
var stringId = $(this).attr("id"); // this will return p_100
var stringId = $(this).attr("id").split('_')[1]; // this will return 100
var attr= $(this).attr("href"); // this will return all href attribute value
UPDATE
//href="test.php?id=100&status=pending&time=2009"
var attrFromAnchor= $(this).attr("href").split('?')[1].split('&')[0].split('=')[1]; // returns 100
There are a lot of good solutions here but I figured I'd post my own.
Here's a quick little function I threw together which will parse a query string in the format from either window.location.search or from a provided search string value;
It returns a hash of id value pairs so you could reference it in the form of:
var values = getQueryParams();
values['id']
values['blah']
Here's the code:
/*
This function assumes that the query string provided will
contain a ? character before the query string itself.
It will not work if the ? is not present.
In addition, sites which don't use ? to delimit the start of the query string
(ie. Google) won't work properly with this script.
*/
function getQueryParams( val ) {
//Use the window.location.search if we don't have a val.
var query = val || window.location.search;
query = query.split('?')[1]
var pairs = query.split('&');
var retval = {};
var check = [];
for( var i = 0; i < pairs.length; i++ ) {
check = pairs[i].split('=');
retval[decodeURIComponent(check[0])] = decodeURIComponent(check[1]);
}
return retval;
}
To get the value of the query string from the URL without string parsing you can do:
window.location.search.substr(1)
If you want the name of the page before the ? you still need to do a little string parsing:
var path = window.location.pathname.replace(/^.*\/(.*)$/,'$1');
var query = path + window.location.search;
//If your URL is http://www.myserver.com/some/long/path/big_long%20file.php?some=file&equals=me
//you will get: big_long%20file.php?some=file&equals=me
Hope this helps!
Cheers.
Here's a concise (yet complete) implementation for getting ALL name/value pairs from a query string:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {};
var tokens;
while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
No need for jQuery, this solution works on all browsers:
function querySt(ji)
{
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
return "";
}
Answers here are outdated now.
See this solution using Vanilla JavaScript (ES5)
var qd = {}; // qd stands for query dict
document.getElementById("p_100")[0].href.split("?")[1].split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,]})
I like to pretend it's oneliner, but I was told it's not. hmm...Who would split chained function calls on new lines anyways, right?
example:
"test.php?id=100&status=pending&time=2009"
> qd
id: ["100"]
status: ["pending"]
time: ["2009"]
// values can also be obtained like this
> qd.id[0] // "100"
> qd["id"][0] // "100"
*It returns arrays, because it is optimized for multi-valued keys. Look here for dummy solutions (without arrays).
note: To teach old browsers the new .forEach you can inject this polyfill from Mozilla (MDN).

Categories