0

I have a complex array, with structure like the following..

array(3) {
  ["status"]=>
  int(1)
  ["data"]=>
  array(113) {
    [0]=>
    array(3) {
      ["id"]=>
      string(6) "838424"
      ["language"]=>
      NULL
      ["work_start_date"]=>
      string(19) "2003-04-28 00:00:00"
    }
    [1]=>
    array(3) {
      ["id"]=>
      string(6) "839062"
      ["language"]=>
      NULL
      ["work_start_date"]=>
      string(19) "2014-01-15 12:53:00"
    }
  }
}

I can get the "id" of a certain element by using something like the following..

print $my_array["data"]["0"]["id"] . "\n";

But what I want to do is loop through the 0,1 etc elements, and I don't know how to do that. I thought something like the following would do it, but it doesn't work.

foreach ($my_array["data"] as $key) {
   print $my_array["data"][$key]["id"] . "\n";
}

Any insight would be appreciated

1
  • 1
    I assure you, your array keys are not arrays. Commented Jan 17, 2014 at 21:48

2 Answers 2

3

You are a little off on your foreach syntax.

You should either do:

foreach($my_array['data'] as $item) {
    print $item['id'] . "\n";
}

Or

foreach($my_array['data'] as $key => $item) {
    print "The item at index position '" . $key . "' has an id of '" . $item['id'] . "'\n";
}

In the first case where foreach syntax with single variable name is used, you actually have no information on the key itself, you only get the values at each index location. This sort of syntax is usually only useful for numerically indexed arrays (which you have in this case).

In the second syntax, you get a variable for both the key and the value that you can reference. This is usually most useful for iterating associative arrays, or for iterating numerical arrays where you need to reference the index position.

In either case, the value present in $item would hold only the value for that array element, you would not need reference back to the containing $my_array variable to access this data.

Sign up to request clarification or add additional context in comments.

Comments

0

Try something like:

foreach (array_keys($my_array["data"]) as $key) {
  print ...
}

1 Comment

This might not add much value to the OP's understanding of their original error... that being a simple misunderstanding of the foreach() syntax.

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.