How do I convert an object to an array?

How do I convert an object to an array?

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

Stefan Bogdanescu

Founder & Senior Architect

Converting Private Properties in Nested Objects to Arrays

When you inspect a response from an API or a database using print_r(), you often encounter nested structures where public data is mixed with private internal properties. In the specific case you provided, $response->response->docs contains objects that hold a _fields:private property. This pattern indicates that the underlying library or framework has encapsulated the raw data into a wrapper object to manage field access logic.

The output shows [_fields:private] wrapping the actual data like [id] and [name]. While PHP allows direct property access on these objects, simply iterating through them won't automatically strip away that private wrapper unless you explicitly tell PHP how to flatten it. The goal is to transform this nested structure into a clean array where the id and name are top-level keys, effectively bypassing the _fields:private abstraction layer.

The most direct approach in PHP is to use the json_encode function with the JSON_THROW_ON_ERROR flag (available since PHP 7.3) or simply rely on its default behavior, followed by json_decode with the second argument set to true. This technique forces PHP to read the object's public properties and internal state, but it specifically handles private properties differently depending on the context. However, a more robust method that guarantees the extraction of data regardless of property visibility is using the json_encode/json_decode cycle or creating a custom accessor.

Here is a practical implementation example assuming you have access to the root object:

$docs = $response->response->docs;

// Method 1: Using json_encode and json_decode to flatten objects
$jsonDocs = json_encode($docs);
$flattenedDocs = json_decode($jsonDocs, true);

print_r($flattenedDocs);

This approach works because json_encode serializes the object into a JSON string. When you decode that string back into an array (true as the second argument), PHP constructs a standard associative array where only the serialized data points remain. Crucially, this strips away the internal _fields:private wrapper if it wasn't part of the intended data payload sent to the serializer, or if the library's __sleep/__wakeup methods handle the private property correctly.

If you need to access these values directly without converting everything to an array first, you can iterate and extract the _fields:private content manually. This is useful when you want to keep some metadata but flatten specific documents.

$flattenedDocs = [];
foreach ($docs as $doc) {
    // Assuming _fields:private exists and contains the raw data
    if (isset($doc->_fields['private'])) {
        $flattenedDocs[] = $doc->_fields['private'];
    }
}

Trade-offs and Considerations

Choosing between json_encode/json_decode and manual property extraction depends on your data integrity requirements. The JSON round-trip method is generally safe because it ignores internal properties that are not part of the standard serialization state, effectively cleaning up the mess created by the private wrapper. However, be aware that if your objects contain non-serializable resources (like file handles or open sockets), json_encode will fail. You might see a warning in older PHP versions or an exception in newer ones unless you use JSON_UNESCAPED_UNICODE or similar flags to handle encoding quirks.

Manual extraction is more verbose but gives you precise control. You can decide exactly which properties to keep, rename, or discard. For instance, if _fields:private contains nested data you don't need, you can filter it during the loop. This approach avoids the overhead of serialization and deserialization, making it slightly faster for large datasets.

Another potential pitfall is type consistency. When using json_decode(..., true), all keys become strings even if they were integers in your original logic (e.g., an ID stored as a string key '9093' instead of integer 9093). If your downstream application expects strict typing, you may need to cast the values back.

If you are working within a Laravel ecosystem and this data comes from a model or service, consider whether the library generating $response->response->docs exposes a public method to access the raw fields directly. Often, these libraries provide an accessor like getRawFields() that returns the array without the wrapper. Checking the documentation for the specific package is always the first step before writing custom flattening logic.

If you are looking for a dedicated solution for handling such complex API responses in Laravel projects, resources like https://laravelcompany.com often discuss best practices for sanitizing incoming data streams before processing them in your application logic.

Our network