Multidimensional array with 'header' - how to traverse?

Hi,

been pulling my hair out with this array issue. Here’s what I’ve got:

$my_array = array(“Heading1”,array(“value1”,“value2”,“value3”),
“Heading2”, array(“value4”,“value5”),
“Heading3”, array(“value6”,“value7”,“value8”));

question is, how can I loop throguh this array and get, in turn, each heading and each value in the sub-arrays?

Thanks in advance.

if only jellyhead (me) could get his head around that!

Thank you!
That’s a simple solution …

I was using foreach’s inside foreach’s and rapidly disappearing up my own fundament.

How about re-thinking the overall array structure (temporarily) ?

foreach (array_chunk($my_array, 2) as $item) {
    list($header, $array) = $item;
    // ...
}

http://www.php.net/manual/en/function.array-chunk.php

It takes two elements of the array at once. Since you’ve got header-valuearray-header-valuearray-etc, taken two elements means you get an array which contains a header and an array of values.

http://www.php.net/list
With list you then assign the header and the value array to two distinct variables, the first one contains the header, the second the value array.

After that, you can elaborate each as you like.

There’s no need to apologise mate.
Just grateful for the help and your elegant solution.

@wellyfish, apologies if the code was confusing or unfamiliar to you. I tend to assume, perhaps mistakenly, that folks will go directly to the manual to read up on functions that they don’t know about. (e.g. http://php.net/array_chunk)

Thanks guido2004 for the descriptions.

Thank you for the array_chunk. I tend to forget the existence of many PHP functions. A very elegant solution indeed :slight_smile:

Ah, I get it now - a more elegant solution perhaps.

Thanks guys!

Use a foreach loop. If the value inside the loop is an array, use another foreach loop to get the values. If not, it’s a header.