# loop through 3-D array based on key conditions

Printable View

• 05-25-2011, 09:44 PM
mathceleb
loop through 3-D array based on key conditions
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.

PHP Code:

``` foreach (\$codes as \$city){    foreach (\$city as \$state){              foreach (\$state as \$school){           if (\$city == "Chicago" && \$state == "Illinois") {array_push(\$school_match,\$school);}       }    } }  ```
• 05-25-2011, 09:56 PM
Inigoesdr
Why are the states inside of cities? That's craziness.
PHP Code:

``` 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() or array_key_exists() before looping to prevent potential errors from foreach() if you misspell them.
• 05-25-2011, 10:09 PM
mathceleb
Thanks!

Regarding the array setup, that is the way it was setup before I took over.
• 12-12-2012, 02:21 PM
facit
Quote:

Originally Posted by mathceleb
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.