...

View Full Version : loop through 3-D array based on key conditions



mathceleb
05-25-2011, 10:44 PM
I have a 3-D array with keys as [city][state][school]. Is there a way to loop through conditionally based on keys, so go through each school based on a city = Chicago and State = Illinois? Or do I have to do a traditional foreach and go through all values and pick off the ones that match Chicago and Illinois?

Doing the long way, I have the code below. the problem is, that 3-D array contains 6000 entries, and I have to crank through it a few thousand times.


foreach ($codes as $city){

foreach ($city as $state){

foreach ($state as $school){
if ($city == "Chicago" && $state == "Illinois") {array_push($school_match,$school);}
}

}


}

Inigoesdr
05-25-2011, 10:56 PM
Why are the states inside of cities? That's craziness.

foreach($codes['Chicago']['Illinois'] as $school)
{
// loop code
}

// or

$city = 'Chicago';
$state = 'Illinois';
foreach($codes[$city][$state] as $school)
{
// loop code
}

You probably want to check to see if the keys exist with isset() (http://php.net/isset) or array_key_exists() (http://php.net/array_key_exists) before looping to prevent potential errors from foreach() (http://php.net/foreach) if you misspell them.

mathceleb
05-25-2011, 11:09 PM
Thanks!

Regarding the array setup, that is the way it was setup before I took over.

facit
12-12-2012, 03:21 PM
Doing the long way, I have the code below. the problem is, that 3-D array contains 6000 entries, and I have to crank through it a few thousand times.

With that many entries being checked that many times, I would strongly suggest using a relational database. If you can't or won't install mysql (or some other sql) server software, you should look at sqlite. It uses a local file to store the database and is almost as fast as other sql implementations.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum