Page 1 of 1

Looping Through Multidimensional Array?

Posted: Wed Nov 03, 2010 6:17 am
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.

Re: Looping Through Multidimensional Array?

Posted: Wed Nov 03, 2010 7:08 am
by requinix
Just use two loops.

Code: Select all

foreach ($array as $person => $items) {
    foreach ($items as $item) {
        // print your table row
    }
}

Re: Looping Through Multidimensional Array?

Posted: Wed Nov 03, 2010 8:10 am
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.

Re: Looping Through Multidimensional Array?

Posted: Wed Nov 03, 2010 11:18 am
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. :)