Skip to main content
Adrien_
Known Participant
March 13, 2012
Answered

Stupid question about arrays

  • March 13, 2012
  • 1 reply
  • 1261 views

So I was messing in PHP the last few weeks and I like how they do their arrays, essentially mapping a value to value:

    public function setParams(array $params)

    {

        foreach ($params as $key=>$value) {

            $this->setParam($key, $value);

        }

        return $this;

    }

My question is, if I wanted to do this in AS3.0 I would do something like:

public function setParams(params:Array){

     foreach (params as //something)

     {

          setParams(key:String, value:String);

     }

}

Can some one fill in the //something spot for me, thats where Im stuck >_>

thanks.

This topic has been closed for replies.
Correct answer kglad

if you want to pass an array of key,value,key,value, then do so.  there's no significant difference from what i showed:

public function(keyvalueA:Array):Object{

var obj:Object={};

for(var i:int=0;i<keyvalueA.length;i+=2){

obj[keyvalueA]=keyvalueA[i+1];

}

return obj;

}


if the values are arrays, you would use the following to trace all the array elements of all the value arrays:

public function(keyvalueA:Array):Object{

var obj:Object={};

for(var i:int=0;i<keyvalueA.length;i+=2){

obj[keyvalueA]=keyvalueA[i+1];

if(keyvalueA[i+1] is Array){

for(var j:int=0;j<keyvalueA[i+1].length;j++){

trace("value:",i,"element:",j,keyvalueA[i+1]);

}

}

}

return obj;

}

1 reply

kglad
Community Expert
Community Expert
March 13, 2012

use an associative array (ie, object):

public function(keyA:Array,valueA:Array):Object{

// error check to ensure keyA.length==valueA.length

var obj:Object={};

for(var i:int=0;i<keyA.length;i++){

obj[keyA]=valueA;

}

return obj;

}

Adrien_
Adrien_Author
Known Participant
March 13, 2012

Not sure if thats what I want.....I mean it looks like im storing key and value in an object when I need to be setting key and value to a already defined set method as showen in my op.

your essentially passing in two arrays, checking the length and storing them in an object...if im correct. where as the array i would pass in would have:

array[key, value, key, value...]

and for every key I need its coresponding value to set it into my method that takes both a key and a value....

Maybe I am missing something?

I sort of get it now as I looked up:

http://livedocs.adobe.com/flex/3/html/help.html?content=10_Lists_of_data_4.html

kglad
Community Expert
Community Expert
March 13, 2012

if you want to pass an array of key,value,key,value, then do so.  there's no significant difference from what i showed:

public function(keyvalueA:Array):Object{

var obj:Object={};

for(var i:int=0;i<keyvalueA.length;i+=2){

obj[keyvalueA]=keyvalueA[i+1];

}

return obj;

}