convert php array into single JSON object

convert php array into single JSON object

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

Stefan Bogdanescu

Founder & Senior Architect

Merging PHP Arrays into a Single JSON Object

When working with serialized data or API responses, you often encounter structures where multiple single-key arrays are grouped together. In your specific case, json_encode correctly identified that the input is an array of arrays, resulting in a JSON format like [{"03-13-2012":"Jazz"},{"07-19-2012":"Pop"}]. The goal is to collapse this structure into a single object where keys from the sub-arrays are merged at the top level: {"03-13-2012":"Jazz","07-19-2012":"Pop"}.

Achieving this transformation requires flattening the nested array structure before encoding it to JSON. The logic is straightforward: you must iterate through the outer array, extract the key-value pairs from each inner associative array, and collect them into one unified collection.

Implementing the Flatten Logic in PHP

The most robust way to handle this in PHP is by leveraging a loop that aggregates the data before serialization. Since your source material shows an Array of Arrays where each sub-array contains exactly one key-value pair, you can simplify the aggregation process significantly.

Here is a practical implementation pattern:

$rawData = [
    ['03-13-2012' => 'Jazz'],
    ['07-19-2012' => 'Pop']
];

$mergedObject = [];

foreach ($rawData as $item) {
    foreach ($item as $key => $value) {
        $mergedObject[$key] = $value;
    }
}

$jsonString = json_encode($mergedObject);

This approach explicitly iterates through every inner array ($item) and then through its keys. By assigning $mergedObject[$key] = $value, you effectively merge the sub-arrays into a single associative array. When json_encode processes this final structure, it outputs a standard JSON object without the surrounding brackets that indicate an array of objects.

Handling Key Collisions

A critical detail to consider during this flattening process is key uniqueness. If your source data contains multiple entries with the same date key (e.g., two entries for 03-13-2012), the last iteration in the loop will overwrite the previous value. In many data processing scenarios, this might be acceptable if you only care about the latest state. However, if data integrity is paramount and duplicates exist, you should validate that keys are unique before merging or decide on a strategy to handle conflicts, such as appending a timestamp or throwing an error.

The jQuery Alternative

If you need to perform this conversion entirely in JavaScript after receiving the JSON string from the server, json_encode will not be available. You must parse the original array structure first and then merge it using JavaScript object destructuring or the spread operator.

Assuming you receive the string [{"03-13-2012":"Jazz"},{"07-19-2012":"Pop"}]:

const rawData = [
  {"03-13-2012": "Jazz"},
  {"07-19-2012": "Pop"}
];

// Merge arrays into a single object
const mergedObject = {};
data.forEach(subArray => {
    Object.assign(mergedObject, subArray);
});

// Or using the spread operator (ES6+)
const mergedObject2 = {...rawData[0], ...rawData[1]};

Using Object.assign within a loop mimics the PHP logic by iterating through each sub-object and copying its properties into the target object. This ensures that even if you have more than two items in the list, they are all merged sequentially.

Why Not json_decode First?

It is worth noting that you could technically use json_decode to convert the JSON string back into a PHP array structure, perform the merge, and then json_encode it again. While this works, it adds unnecessary overhead if you already have the raw array in memory. Direct manipulation of the native array structure is generally more performant than serializing and deserializing multiple times within the same request lifecycle.

Final Considerations

The transformation from an array of single-key objects to a single flat object is a common requirement when normalizing data before storage or transmission. By explicitly iterating and merging, you maintain full control over key collisions and can debug the intermediate state easily using print_r or var_dump. This method ensures that your final JSON output matches the expected structure precisely, avoiding the ambiguity of nested array syntax.

Our network