We help IT Professionals succeed at work.

get key position inside foreach loop  in complex array

antonumia
antonumia asked
on
I am iterating through a complex array created from wierd xml.
I want to store the position of each key as part of the form that gets populated submits back into the array

The array looks like:

Array
(
    [Data] => Array
        (
            [Item] => Array
                (
                    [0 attr] => Array
                        (
                            [id] => 1
                            [name] => Animation For Acorn Property Group
                            [body] => assets/text/news_acorn.txt
                            [date] => 17/12/08
                            [thumbnail] => assets/images/news_acorn_th.jpg
                        )

                    [0] =>
                    [1 attr] => Array
                        (
                            [id] => 2
                            [name] => Crosby Lend Lease Hub development
                            [body] => assets/text/news_hub.txt
                            [date] => 17/12/08
                            [thumbnail] => assets/images/hub3_th.jpg
                        )
...

and my code that pulls out the data:

      $mystr = '';
      foreach ($data["Data"]["Item"] as $key=>$value) {
            if(is_array($value)) {
                  $mykeys = array_keys($value);
                  foreach ($mykeys as $skey=>$svalue) {
                        $mystr .= getHtml($svalue, $value[$svalue], $pos);
                  }
...

i've tried $pos = key($data["Data"]["Item"]) after the first foreach

but I get only '0 attr' back for all values.

Any way to return the position of  [0 attr], [1 attr], etc?

thanks,

antonumia
Comment
Watch Question

Commented:
foreach ($data["Data"]["Item"] as $key=>$value) {

$key by itself is the key position in the loop.
Commented:
foreach ($data["Data"]["Item"] as $key=>$value) {
  echo $key;
}


will output 1,2,3,4,5,6,7,8 etc.

Author

Commented:
that nearly worked although it returned
1 attr, 1, 2 attr, 2

I think it's the array at fault.
and bit of fiddling and this worked great!

thanks

a

Explore More ContentExplore courses, solutions, and other research materials related to this topic.