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..

1

3 Answers 3

3

Include the index (key) in the foreach loop.

foreach($json_obj1['result'] as $index => $item)
{
    // access to the number
    $index
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.