Looping Through Multidimensional Array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
djlex1928
Forum Commoner
Posts: 31
Joined: Sun Sep 19, 2010 3:23 pm

Looping Through Multidimensional Array?

Post by djlex1928 »

First, here is my array:

[text]Array
(
[Alex] => Array
(
[0] => Array
(
[id] => 265
[date] => 021110
[spent] => 55.20
)

[1] => Array
(
[id] => 278
[date] => 031110
[spent] => 23.60
)

[Rachel] => Array
(
[0] => Array
(
[id] => 241
[date] => 011110
[spent] => 9.70
)

)

)
[/text]

Basically if the above array is returned I want to loop through and output in a table as follows:

Name | Date | Spent
Alex | 02/11/10 | £55.20
Alex | 03/11/10 | £23.60
Rachel | 01/11/10 | £9.70

The problem I have is the names, Alex and Rachel in another query could become Mike and Julie.

Is there any way I can eliminate the names when looping through but still being able to identify which person it is when outputting to the table?

Just so you know this is not an array I can edit, the array is returned from a SOAP server I do not own.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Looping Through Multidimensional Array?

Post by requinix »

Just use two loops.

Code: Select all

foreach ($array as $person => $items) {
    foreach ($items as $item) {
        // print your table row
    }
}
jefffan24
Forum Commoner
Posts: 72
Joined: Mon Nov 02, 2009 8:18 am

Re: Looping Through Multidimensional Array?

Post by jefffan24 »

Another way to do it would be:

Code: Select all

foreach ($array as $person) {
    $person[array_value_here];
   // for example $person[id];
}
Doing this will allow for just one loop but still access the second array.
djlex1928
Forum Commoner
Posts: 31
Joined: Sun Sep 19, 2010 3:23 pm

Re: Looping Through Multidimensional Array?

Post by djlex1928 »

tasairis wrote:Just use two loops.

Code: Select all

foreach ($array as $person => $items) {
    foreach ($items as $item) {
        // print your table row
    }
}
Thanks a million, got me up and running. :)
Post Reply