View Full Version : Resolved Searching through a multidimensional array.
jlizarraga
06-04-2009, 12:17 AM
EDIT: Forgot to mention that this is for an AS2 document!
Hi all,
Does anyone have a function for searching multi-dimensional arrays (I only need to look for string matches)? I couldn't find one in Google and can't figure it out myself.
I'm guessing that you would iterate through the array, then check if each value is an array, and if so iterate through that - rinse and repeat. typeof on an array yields "object" so I'm a bit stuck.
Thanks!
jlizarraga
06-04-2009, 06:45 PM
I ended up finding a detailed thread on this subject which concluded that a foolproof method to see if something is an array is (at least in AS2) not entirely possible.
Luckily, the arrays I'm dealing with are created from an XML response from a server, parsed by GreenSock's XMLParser class, which transforms an XML document into a multidimensional associative array. With the GreenSock parser, if an object in the array does not have a "value" property, it is safe to assume that it contains more nodes (parsed into arrays).
So this is my final working function (also the first recursive function I've ever written, yay!):
function checkArray (pArray:Array, pWhich:String, pAttribute:String, pValue:String) {
trace("checkArray()");
var oReturn = "";
for (var i in pArray) {
var oBreak = false;
for (var j=0; j<pArray[i].length; j++) {
if (typeof(pArray[i][j].value) == "undefined") {
// This node contains more nodes.
oReturn = checkArray(pArray[i][j], pWhich, pAttribute, pValue);
if (typeof(pAttribute != "undefined")) {
// If we're filtering by attribute, see if we have a match.
if(oReturn != ""){
oBreak = true;
break;
}
}
} else if (i == pWhich) {
// We want the value of this node.
if (typeof(pAttribute) == "undefined"){
// Attributes don't matter.
oReturn = pArray[i][j].value;
oBreak = true;
break;
} else if (typeof(pArray[i][j][pAttribute]) != "undefined") {
// We want a specific attribute.
if (pArray[i][j][pAttribute] == pValue) {
oReturn = pArray[i][j].value;
oBreak = true;
break;
}
}
}
} // for (length)
if (oBreak == true) {
trace("Found " + oReturn);
break;
}
} // for (in)
return oReturn;
}
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.