Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Mar 2010
    Posts
    235
    Thanks
    39
    Thanked 6 Times in 6 Posts

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

       }




  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,642
    Thanks
    2
    Thanked 405 Times in 397 Posts
    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.

  • Users who have thanked Inigoesdr for this post:

    mathceleb (05-25-2011)

  • #3
    Regular Coder
    Join Date
    Mar 2010
    Posts
    235
    Thanks
    39
    Thanked 6 Times in 6 Posts
    Thanks!

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

  • #4
    New to the CF scene
    Join Date
    Dec 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by mathceleb View Post
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •