Parsing JSON array with PHP foreach

Parsing JSON array with PHP foreach

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Parsing JSON Array with PHP foreach

When working with analytics APIs or external data feeds, you often encounter nested JSON structures. The immediate goal is usually to flatten these structures and iterate over specific fields. Consider a scenario where you have successfully decoded a JSON payload into an object and need to access the values array within each item of a data array.

$user = json_decode(file_get_contents($analytics));
foreach($user->data as $mydata) {
    echo $mydata->name . "\n";
}

This loop works perfectly fine, outputting the name property for every element in the data collection. However, attempting to access the values array directly inside this same structure often leads to an error when you try to iterate over $user->data->values.

The root cause lies in how PHP represents JSON data after decoding. The json_decode function returns a standard PHP object or array depending on your configuration. In the provided example, the code assumes that the values property exists directly on the parent object containing the name. Let's examine the actual JSON structure to see why this assumption fails:

{
   "data": [
      {
         "id": "MY_ID/insights/page_views_login_unique/day",
         "name": "page_views_login_unique",
         "period": "day",
         "values": [
            {
               "value": 1,
               "end_time": "2012-05-01T07:00:00+0000"
            },
            {
               "value": 6,
               "end_time": "2012-05-02T07:00:00+0000"
            }
         ]
      }
   ]
}

In this structure, values is a property belonging to an object inside the data array. It is not a sibling of name on the root level, nor is it a direct child of the root data array itself. The syntax $user->data->values attempts to access a property named values on the data variable. Since data is an array containing multiple objects (as indicated by the [...] in the JSON), PHP treats $user->data as the entire array object. Arrays do not have a single values property; they have elements at specific indices.

To fix this, you must iterate through the outer loop and then access the nested values array within each iteration of that loop. The corrected approach requires nesting two loops or using a conditional check to ensure the structure exists before accessing it.

$user = json_decode(file_get_contents($analytics));

foreach ($user->data as $mydata) {
    echo $mydata->name . "\n";
    
    // Check if 'values' exists to avoid warnings or errors
    if (isset($mydata->values)) {
        foreach ($mydata->values as $values) {
            echo $values->value . "\n";
        }
    }
}

This pattern ensures that you are accessing the values array relative to the current $mydata object, not the root data container. It is crucial to verify that the JSON structure matches your expectations. If the API response changes or if a specific entry lacks the values field entirely, using isset() prevents PHP from throwing "Undefined property" notices.

Another consideration involves strict type checking. While json_decode returns an object by default for associative arrays, some developers prefer converting the result to an array using JSON.decode($json, true). This change allows you to use $user['data'] syntax instead of $user->data, which can sometimes make debugging nested structures easier if you are used to working with array access operators. However, sticking to object notation is standard when dealing with JSON APIs that return named properties.

When handling large datasets, iterating through every record to print values might not be the most efficient approach. If you only need the sum of all values or a specific metric from the values array, calculating that during the iteration avoids creating intermediate arrays in memory. For example, accumulating a total count inside the loop keeps memory usage low while processing the stream of data.

Understanding the hierarchy of your JSON payload is the first step to debugging these issues. Always visualize the tree structure before writing your loops. If a property feels like it should be accessible directly on the parent but isn't, remember that arrays in PHP do not expose properties on their collection level unless explicitly defined as such.

Our network