Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Iterating over muli-dimensional arrays.

Status
Not open for further replies.

shagymoe

Programmer
Apr 20, 2001
72
US
Lets say I have a multi-dimensional array like this:
Code:
$file_mod_info[$mod_type][$mod_file_path][$index]='mod_string';
Then I iterate over it like so:
Code:
foreach ($file_mod_info as $mod_type => $mod_file_path_array) {
  foreach ($mod_fil_path_array as $mod_file_path => $index_arrray) {
    foreach ($index_array as $index => $mod_string) {
      echo 'Mod Type: ' . $mod_type . "\n" .
             'Mod File Path: ' . $mod_file_path . "\n" .
             'Mod Index: ' . $mod_index . "\n" .
             'Mod String: ' . $mod_string . "\n";
      }
    }
  }
}
I get exactly what I'm looking for, but is there a better way to go about this? It seems klugey.

I'm trying to use this approach on a separate problem where I want to fill an array with a module name and the file it will modify. The problem is that two modules could modify the same file and modules have multiple entries...so the repetition of both types of info prevent using either as an associative array key. My aim is to identify modules which will modify the same file and inform the user, but I'm finding it a bit difficult. Maybe I just can't get my brain around it today...I don't know.

Any suggestions on working with info like this? Array functions like array_intersect or array_diff won't do what I want and I'm banging my head on the table....
 
What about writing a recursive function that follows into the existing depth of the array initially passed?

This is not unlike traversing a tree in any kind of multi dimensional branch structure.
 
I haven't really written any recursive functions, although I understand the concept, I am new to implementing it on anything other than a trivial problem. Looks like I should give it a deeper look.

I was also thinking that maybe the OO approach would be better, but again I don't instinctively use OO.

Thanks for the suggestion.

Shagy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top