David King
David King

Reputation: 2040

Flash storing strings as keys in array

in php I could do:

$prices['ford']['mondeo']['2005'] = 4500;
$prices['ford']['mondeo']['2006'] = 5500;
$prices['ford']['mondeo']['2007'] = 7000;

and could do:

echo sizeof($prices['ford']); // output 1
echo sizeof($prices['ford']['mondeo']) //output 3

how can I achieve it in Flash. Flash doesn't seems to like STRINGS as ARRAY KEYS, does IT ?

Upvotes: 0

Views: 685

Answers (3)

kkyy
kkyy

Reputation: 12460

To have associative array -like functionality, you can use an Object;

var prices:Object = new Object();
prices.ford = new Object();
prices.ford.mondeo = new Object();
prices.ford.mondeo['2005'] = 4500;
prices.ford.mondeo['2006'] = 5500;
prices.ford.mondeo['2007'] = 7000;

or simply

var prices:Object = {
  ford: {
    mondeo: {
      2005: 4500,
      2006: 5500,
      2007: 7000
    }
  }
};

Actionscript doesn't have a built in function resembling sizeof in php, but you can easily write one of your own:

function sizeof(o:Object):Number {
    var n:Number = 0;
    for (var item in o)
        n++;
    return n;
}

And just use it like in php:

trace(sizeof(prices['ford'])); // traces 1
trace(sizeof(prices['ford']['mondeo'])); // traces3

Upvotes: 2

Amarghosh
Amarghosh

Reputation: 59451

var array:Array = [];
array['name'] = "the name";
array['something'] = "something else";
trace(array.length);

It traces 0. So yeah, flash doesn't really like strings as array keys though it is allowed. Array is a dynamic class (like Object) where you can add properties to individual objects as you want. array['name'] = "myname" is same as array.name = "myname".

That said, you can assign an array to array['name'] and read its length.

var array:Array = [];
array['name'] = new Array();
array.name.push(1, 2, 3);
trace(array.length);//traces 0
trace(array.name.length);//traces 3

Upvotes: 1

grapefrukt
grapefrukt

Reputation: 27045

Arrays are indexed by integers in Flash, if you want to index on a string use an Object instead.

Upvotes: 1

Related Questions