0

I got an array which looks like this:

{
"result": {
    "549051622": {...stuff}
    "549051623": {...stuff}
    "549051624": {...stuff}

and I'm doing a foreach loop to get all the items

 foreach($json_obj1['result'] as $item)
{
    // access to the number
    $item[???]
 }

But how do I get the "549051622" when im refering to the array object as $item?

Found nothing yet for this very problem..

Eric Random
  • 158
  • 9
  • 1
    possible duplicate of [PHP: Get the key from an array in a foreach loop](http://stackoverflow.com/questions/10992005/php-get-the-key-from-an-array-in-a-foreach-loop) – Derek Aug 08 '14 at 15:55

3 Answers3

3

Include the index (key) in the foreach loop.

foreach($json_obj1['result'] as $index => $item)
{
    // access to the number
    $index
}
Derek
  • 3,438
  • 1
  • 17
  • 35
1

foreach($json_obj1['result'] as $key => $item) then access $key.

Alternatively, try:

foreach(array_keys($json_obj1['result']) as $key) - I use this sometimes when I really don't care about the items themselves, just the keys.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Arrays use pointers to track the current item they are at... Using reset, end, next, current, key are all functions super useful if you want to micro your own array traversal.

For example, if you want the key of the first item of an array that the point hasn't moved, you can use

key($json_obj1['result'])

to retrieve the key of the current item...

This may not work in a foreach context though i've never tried it!

Mathieu Dumoulin
  • 12,126
  • 7
  • 43
  • 71