SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2012
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Nested Array Iteration... Is there a cleaner approach than this?

    Here's a simplified piece of my array structure. I'm trying to drill down and loop only through the months in the first department contained at the "monthly" level. The problem is, that department's name is used as the array's key and that will change per data set.

    Is there a better way than calling multiple foreach loops and then breaking the parent loop after it has called its first iteration? At this scaled down version, the code doesn't look so bad, but this could get out of hand for large more complex data sets.

    Code:
    [
       array => overall
          array => baseline
              n/a
          array => monthly
              array => some_anonymous_department_name
                  jan     => 77%
                  feb     => 99%
                  march => 44%
              array => some_anonymous_department_name_2
                  jan     => 79%
                  feb     => 33%
                  march => 45%
    ]
    Code:
    foreach($this->data['overall']['monthly'] as $dept) {
       foreach($dept as $month => $score)
          echo $month . '<br />';
       break;
    }

  2. #2
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    72 Post(s)
    Tagged
    0 Thread(s)
    Not much of one, but...
    PHP Code:
    $dept array_shift($this->data['overall']['monthly']);
    foreach(
    $dept as $month => $score)
      echo 
    $month '<br />'
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.

  3. #3
    SitePoint Enthusiast
    Join Date
    Jun 2012
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's an angle I hadn't considered, particularly useful if you don't need the original data set be kept intact. I'll keep this strategy in mind. Thanks.


Bookmarks

Posting Permissions

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