CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   PHP (http://www.codingforums.com/forumdisplay.php?f=6)
-   -   loop through 3-D array based on key conditions (http://www.codingforums.com/showthread.php?t=227815)

mathceleb 05-25-2011 09:44 PM

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);}
      }

   }





Inigoesdr 05-25-2011 09:56 PM

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.

mathceleb 05-25-2011 10:09 PM

Thanks!

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

facit 12-12-2012 02:21 PM

Quote:

Originally Posted by mathceleb (Post 1094381)
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.


All times are GMT +1. The time now is 01:54 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.