AS3/Flash: XML to array - arrays

How may I populate an array formated like this?:
var names:Array = [{label:"JAMES"}, {label:"JANE"}, {label:"JAMEL"}...];
From a XML like this one?:
<a>
<ap>
<name>JAMES</name>
<age>36</age>
</ap>
</a>
This is for AutoComplete components.
UPDATE, to start with something more suitable to my skills. THIS:
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>
TO THIS:
var list:Array = [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}...];

const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const list:Array = new Array();
//xml..label.(trace(text()));
xml..label.(list.push({label:text()}));
// now we have an array:
// [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}, {label:"..."}]
I recommend to read the AVM2 specification and to pay special attention to namespaces. Seriously. It's interesting and it's fun!
Hmmm... Alternative boring way:
const list:Array = new Array();
const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const labels:XMLList = xml..label;
for each(var node:XML in labels)
{
trace(node);
var arrayItem:Object = new Object();
arrayItem.label = node.text(); // or node.toString() or .toJSON() or .to...
arrayItem.name = node.name();
// added only for debug-trace:
arrayItem.toString = function():String
{
var result:String = '{', delimiter:String = '';
for(var key:String in this)
if(key !== 'toString')
result += delimiter + key + ':"' + this[key] + '"',
delimiter ||= ', ';
return result + '}';
}
// add item to list:
list.push(arrayItem);
}
trace(list);

Related

How can I Paginate data which are in array?

I am using Laravel 5.7. I construcet an array like below:
$games = GameResource::collection(Game::all());
$clientGames = array();
foreach ($games as $game) {
if (!$game->user->inRole('admin')) {
array_push($clientGames, $game);
}
}
How can I paginate this array in Laravel?
I used below way to solve my question:
$per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$clientGamesCollection = collect($clientGames);
$currentPageItems = $clientGamesCollection->slice(($currentPage * $per_page) - $per_page, $per_page)->all();
$paginatedItems= new LengthAwarePaginator($currentPageItems , count($clientGamesCollection), $per_page);
$paginatedItems->setPath($request->url());
$pagination = $paginatedItems;

Accessing Items in an Array - AS3

I've got an Object item.movieimage that contain some texts (item:Object) that is retrieve from my database. The text is changing every week automatically.
If I do trace(item.movieimage) the output is something like this :
text1
text2
text3
text4
The words changes as the code is taking them from my database. The database changes the words every week.
Now, I want my AS3 code to display the third element of item.movieimage.
I've tried to do this :
var my_str:String = item.movieimage+",";
var ary:Array = my_str.split(",");
trace(ary[2]);
But it's not working. The output is "undefined".
Do you know how can I access a specific item in the Array that I've created ? Or how can I access the third item of item.movieimage ?
If I do trace(ary);, the output is :
text1,
text2,
text3,
text4,
EDIT :
For infos :
trace(typeof(item.movieimage)) and trace(typeof(ary)) are :
typeof(item.movieimage)=string
typeof(ary)=object
EDIT 2 :
Here's a screen capture of item.movieimage
Screen Cap of item.movieimage
EDIT 3
Here's my code in order to understand how "item.movieimage"is working
//Variables for downloading content from my database to my AS3 code
var urlReqSearchAll: URLRequest = new URLRequest("http://www.myWebSite/searchMovie4.php");
var loader5:URLLoader = new URLLoader();
//downloading content
function searchAll():void {
if (contains(list)){
list.removeChildren();
}
urlReqSearchAll.method = URLRequestMethod.POST;
loader5.load(urlReqSearchAll);
loader5.addEventListener(Event.COMPLETE,complete);
var variables:URLVariables = new URLVariables();
}
//Content Downloaded.
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
hourSaved.data.saved=loader5.data;
products.reverse();
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
displayPage(0);
showList();
}
// If too much items --> creates multiple page
const itemsPerPage:uint = 7;
var currentPageIndex:int = 0;
function displayPage(pageIndex:int):void {
list.removeChildren();
currentPageIndex = pageIndex;
var firstItemIndex:int = pageIndex * itemsPerPage;
var j:int = 0;
var lastItemIndex: int = firstItemIndex + 7; // as lastItemIndex should be 10 more
if (lastItemIndex > products.length) // if lastindex is greater than products length
lastItemIndex = products.length;
for(var i:int = firstItemIndex; i< lastItemIndex; i++){
createListItem( j, products[i]); // j control the position and i points to particular element of array..
j++;
}
next.visible = lastItemIndex < products.length - 1;
if(currentPageIndex==0){
previous.visible=false;
}
}
// Display the information downloded from my database
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
var myFormat:TextFormat = new TextFormat();
myFormat.size = item.title.length > 13 ? 22 : 26
listItem.multiline = true;
listItem.wordWrap = true;
myFormat.align = TextFormatAlign.CENTER;
myFormat.color = 0xA2947C;
myFormat.font = "Ebrima";
myFormat.bold = true;
listItem.defaultTextFormat = myFormat;
listItem.x = 135;
listItem.y = 123+ index * 84;
listItem.width = 200;
listItem.height = 80;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
}
My php file "SearchMovie4.php" is like this :
$products = array();
while ($row = mysql_fetch_array($sql_result)) {
$products[] = array(
"title" => $row["theTitle"],
"movieimage" => $row["movieimage"],
"movielength" => $row["movielength"],
"story" => $row["story"],
);
}
echo json_encode($products);
So, if I do trace(item.movieimage) in AS3 code, it will display all the items in the row movieimage of my database.
If I do trace(item.title) in AS3 code, it will display all the items in the row title of my database.
What I'd like is to be able to do, in my AS3 code, trace(item.movieimage[2]) in order to show me the third item in the row "movieimage".
Well, the text you've provided to the movieimage property of the item object has not the same delimiter as what you have provided to the split() method; in your case the character of comma!
I suspect the delimiter you have, is the "space" character or a new-line character, like the character of carriage retrun.
In the following code snippet, I've used the "space" as the delimiter character:
var item:Object = new Object();
item.movieimage = "text1 text2 text3 text4";
var my_str:String = item.movieimage;
var ary:Array = my_str.split(" ");
trace(ary[2]); // text3
As #someOne said the output shows the list items are each on a new line, so you need to split() against newlines. One of these should work:
// if server uses "\n" newline char
var movies:Array = item.movieimage.split("\n");
// if server uses "\r" carriage return char
var movies:Array = item.movieimage.split("\r");
// if you aren't sure or there's a mixture of newline chars
var movies:Array = item.movieimage.split(/[\r|\n]+/);
Also note that if you have any control over how the server returns these values, you should just return a JSON array (since I see in your screenshot you are already decoding JSON), then you won't have to do any string splitting.

Action Script 3 URLLoader in for loop

I have 7 Arrays to begin with:
private var listArray:Array = new Array();
private var oneArray:Array = new Array();
private var twoArray:Array = new Array();
private var threeArray:Array = new Array();
private var fourArray:Array = new Array();
private var fiveArray:Array = new Array();
private var sixArray:Array = new Array();
listArray contain 6 string element of text file name.
something like:
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
All other array is empty at the moment.
I have wrote a for loop like this:
for (var i:int = 0; i < listArray.length; i++)
{
var urlRequest:URLRequest = new URLRequest(File.documentsDirectory.resolvePath(listArray[i]).url);
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try
{
urlLoader.load(urlRequest);
}catch (error:Error){
trace("Cannot load : " + error.message);
}
}
if without for loop I know I can do this for only one array of data:
private function completeHandler(e:Event):void
{
oneArray = e.target.data.split(/\r\n/);
}
Here I am trying to get something to work like:
oneArray contain the data from 1.txt
twoArray contain the data from 2.txt
so on...
sixArray contain the data from 6.txt
problem:
I known the completeHandler function only execute after for loop looped six times.
is there anyway I could get the correct data to the correct array.
Thanks
Since you are using AIR to load data from the file-system, you don't have to do it asynchronously. You can load it synchronously like this:
function readTxtList(url:String):Array {
var file:File = File.documentsDirectory.resolvePath(url);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var text:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
fileStream.close();
return text.split("\r\n");
}
Now you can just assign each value directly:
var oneArray:Array = readTxtList("1.txt");
var twoArray:Array = readTxtList("2.txt");
// etc
I recommend you to use Dictionary.
Create new Dictionary:
var dict:Dictionary = new Dictionary();
Bind an instance of the URLLoader class to the file name:
var urlRequest:URLRequest = ...
var urlLoader:URLLoader = new URLLoader();
dict[urlLoader] = listArray[i];
In the completeHandler you can get the file name:
trace(dict[e.currentTarget]);
Add if statements to reach your goal.
if (dict[e.currentTarget] == "1.txt")
oneArray = e.target.data.split(/\r\n/);
else if (dict[e.currentTarget] == "2.txt")
twoArray = e.target.data.split(/\r\n/);
...

AS3 Add array to another array

Example of the my problem.
var array_1:Array = new Array();
array_1[0] = [2,4,6,8];
var array_2:array = new Array();
array_2[0] = [10,12,14,16];
array_2[1] = [18,20,22,24];
// and the out come I want it to be is this
trace(array_1[0]) // 2,4,6,8,10,12,14,16,20,22,24
// I did try array_1[0] += array_2[0] but it didn't work currently
Any suggestion would be great.
This will perform what you are looking for and also allows you to add multiple rows of data to array_1 or array_2
var array_1:Array = new Array();
array_1[0] = [2,4,6,8];
var array_2:Array = new Array();
array_2[0] = [10,12,14,16];
array_2[1] = [18,20,22,24];
var combinedArray:Array = new Array();
for( var i:int = 0; i < array_1.length; i++ ) {
combinedArray = combinedArray.concat(array_1[i]);
}
for( i = 0; i < array_2.length; i++ ) {
combinedArray = combinedArray.concat(array_2[i]);
}
trace(combinedArray);
As stated in the comments, you can use the concat method:
var array_1:Array = new Array();
array_1[0] = [2,4,6,8];
var array_2:array = new Array();
array_2[0] = [10,12,14,16];
array_2[1] = [18,20,22,24];
array_1[0] = array_1[0].concat(array_2[0]).concat(array_2[1]);
This, of course, is very messy looking. I am wondering why you are storing arrays inside of other arrays for no discernible reason.

Search Multidimensional Array ActionScript 3

If I have two arrays like the example below, how can I search the first part of each node in the 'score' array with the values in the 'search' array and return the value that is the second part of each node in the 'score' array? Basically in this case I'd want to get 5 and 7.
var score:Array = new Array();
score[0] = ["cat", "3"];
score[1] = ["dog", "5"];
score[2] = ["fish", "0.5"];
score[3] = ["bird", "0.25"];
score[4] = ["horse", "10"];
score[5] = ["cow", "15"];
score[6] = ["iguana", "7"];
var search:Array = ["dog", "iguana"];
Try with this code (using Dictionary):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var score:Dictionary = new Dictionary();
private var search:Array = ["dog", "iguana"];
public function init():void{
score["cat"] = "3";
score["dog"] = "5";
score["fish"] = "0.5";
score["bird"] = "0.25";
score["horse"] = "10";
score["cow"] = "15";
score["iguana"] = "7";
var t1:String = score[search[1]];
var t2:String = score[search[0]];
Alert.show(t1 + ' ' + t2); //prints 5 7
}
]]>
</mx:Script>
</mx:Application>
Or you can do this too:
var t1:String = score["dog"];
var t2:String = score["iguana"];
Or without Dictionary:
<?xml version="1.0" encoding="utf-8"?>
public function init():void{
score[0] = ["cat","3"];
score[1] = ["dog","5"];
score[2] = ["fish","0.5"];
score[3] = ["bird","0.25"];
score[4] = ["horse","10"];
score[5] = ["cow","15"];
score[6] = ["iguana","7"];
for(var j:int = 0;j<search.length;j++){
for(var i:int = 0;i<score.length;i++){
var temp:Array = score[i] as Array;
if(temp[0] == search[j]){
Alert.show(temp[1]);
}
}
}
}
]]>
</mx:Script>
Also you have not used an appropriate way to declare arrays, I recommend using my method or changing the array declaration.

Resources