Flattening Nested Arrays in PHP

Introduction to the concept of flattening nested arrays in PHP, its importance, and common scenarios where this technique is useful.

Understanding the Problem

Explanation of the problem statement with a sample nested JSON structure that needs to be flattened into a single array.

Step-by-Step Solution

  1. Initial Setup

    • Define the nested JSON structure that we want to flatten.
  2. Recursive Function

    • Create a recursive function (flattenArray) that traverses the nested structure and flattens it into a single array.
  3. Filtering Based on Condition

    • Enhance the function to include filtering based on specific conditions, such as filtering nodes where is_active is true.
  4. Implementation in PHP

    • Provide PHP code snippets demonstrating how to implement the flattenArray function.

Example Implementation

phpCopy code<?php
// Example JSON data
$jsonData = '{
    // Your JSON data here
}';

// Decode JSON data into PHP associative array
$data = json_decode($jsonData, true);

// Function to recursively flatten and filter the array structure
function flattenAndFilterArray($data) {
    $result = [];

    // Function to recursively process each node
    $processNode = function($node) use (&$result, &$processNode) {
        if ($node['is_active']) {
            $flattenedNode = [
                'id' => $node['id'],
                'parent_id' => $node['parent_id'],
                'name' => $node['name'],
                'is_active' => $node['is_active'],
                'position' => $node['position'],
                'level' => $node['level'],
                'product_count' => $node['product_count'],
            ];

            // Recursively process children nodes
            foreach ($node['children_data'] as $child) {
                $flattenedChild = $processNode($child);
                $result[] = array_merge($flattenedNode, $flattenedChild);
            }

            // If no children, add the current node itself to result
            if (empty($node['children_data'])) {
                $result[] = $flattenedNode;
            }
        }

        return $flattenedNode ?? [];
    };

    // Process the top-level nodes
    foreach ($data['children_data'] as $node) {
        $processNode($node);
    }

    return $result;
}

// Flatten and filter the array structure
$flattenedAndFilteredArray = flattenAndFilterArray($data);

// Output the flattened and filtered array
echo json_encode($flattenedAndFilteredArray, JSON_PRETTY_PRINT);
?>

for example input is

{
    "id": 88,
    "parent_id": 1,
    "name": "Example.com",
    "is_active": true,
    "position": 1,
    "level": 1,
    "product_count": 826,
    "children_data": [
        {
            "id": 201,
            "parent_id": 88,
            "name": "BREAKFAST",
            "is_active": false,
            "position": 1,
            "level": 2,
            "product_count": 6,
            "children_data": []
        },
        {
            "id": 236,
            "parent_id": 88,
            "name": "BREAKFAST",
            "is_active": true,
            "position": 2,
            "level": 2,
            "product_count": 81,
            "children_data": [
                {
                    "id": 137,
                    "parent_id": 236,
                    "name": "Savoury Breakfasts",
                    "is_active": true,
                    "position": 1,
                    "level": 3,
                    "product_count": 14,
                    "children_data": []
                },
                {
                    "id": 136,
                    "parent_id": 236,
                    "name": "Sweet & Healthy Breakfast",
                    "is_active": true,
                    "position": 2,
                    "level": 3,
                    "product_count": 42,
                    "children_data": []
                },
                {
                    "id": 169,
                    "parent_id": 236,
                    "name": "Hot Breakfast ",
                    "is_active": true,
                    "position": 3,
                    "level": 3,
                    "product_count": 11,
                    "children_data": []
                },
                {
                    "id": 138,
                    "parent_id": 236,
                    "name": "Coffee & Tea  ",
                    "is_active": false,
                    "position": 4,
                    "level": 3,
                    "product_count": 3,
                    "children_data": []
                },
                {
                    "id": 135,
                    "parent_id": 236,
                    "name": "Water, Soft Drinks  & Juices",
                    "is_active": false,
                    "position": 5,
                    "level": 3,
                    "product_count": 21,
                    "children_data": []
                }
            ]
        },
        {
            "id": 98,
            "parent_id": 88,
            "name": "MID MORNING",
            "is_active": true,
            "position": 3,
            "level": 2,
            "product_count": 112,
            "children_data": [
                {
                    "id": 117,
                    "parent_id": 98,
                    "name": "Mini Desserts",
                    "is_active": false,
                    "position": 1,
                    "level": 3,
                    "product_count": 68,
                    "children_data": []
                },
                {
                    "id": 220,
                    "parent_id": 98,
                    "name": "Coffee & Tea  ",
                    "is_active": false,
                    "position": 2,
                    "level": 3,
                    "product_count": 3,
                    "children_data": []
                },
                {
                    "id": 221,
                    "parent_id": 98,
                    "name": "Water, Soft Drinks  & Juices",
                    "is_active": false,
                    "position": 3,
                    "level": 3,
                    "product_count": 21,
                    "children_data": []
                }
            ]
        }

    ]
}

and Desire output is

[
        {
            "id": 201,
            "parent_id": 88,
            "name": "BREAKFAST",
            "is_active": false,
            "position": 1,
            "level": 2,
            "product_count": 6,
            "children_data": []
        },
        {
            "id": 236,
            "parent_id": 88,
            "name": "BREAKFAST",
            "is_active": true,
            "position": 2,
            "level": 2,
            "product_count": 81,
            "children_data": []
        },
        {
            "id": 137,
            "parent_id": 236,
            "name": "Savoury Breakfasts",
            "is_active": true,
            "position": 1,
            "level": 3,
            "product_count": 14,
            "children_data": []
        },
        {
            "id": 136,
            "parent_id": 236,
            "name": "Sweet & Healthy Breakfast",
            "is_active": true,
            "position": 2,
            "level": 3,
            "product_count": 42,
            "children_data": []
        },
        {
            "id": 169,
            "parent_id": 236,
            "name": "Hot Breakfast ",
            "is_active": true,
            "position": 3,
            "level": 3,
            "product_count": 11,
            "children_data": []
        },
        {
            "id": 138,
            "parent_id": 236,
            "name": "Coffee & Tea  ",
            "is_active": false,
            "position": 4,
            "level": 3,
            "product_count": 3,
            "children_data": []
        },
        {
            "id": 135,
            "parent_id": 236,
            "name": "Water, Soft Drinks  & Juices",
            "is_active": false,
            "position": 5,
            "level": 3,
            "product_count": 21,
            "children_data": []
        },
        {  "id": 98,
            "parent_id": 88,
            "name": "MID MORNING",
            "is_active": true,
            "position": 3,
            "level": 2,
            "product_count": 112,
            "children_data": []
        },
        {
            "id": 117,
            "parent_id": 98,
            "name": "Mini Desserts",
            "is_active": false,
            "position": 1,
            "level": 3,
            "product_count": 68,
            "children_data": []
        },
        {
            "id": 220,
            "parent_id": 98,
            "name": "Coffee & Tea  ",
            "is_active": false,
            "position": 2,
            "level": 3,
            "product_count": 3,
            "children_data": []
        },
        {
            "id": 221,
            "parent_id": 98,
            "name": "Water, Soft Drinks  & Juices",
            "is_active": false,
            "position": 3,
            "level": 3,
            "product_count": 21,
            "children_data": []
        }
]

Did you find this article valuable?

Support Mandeep Singh Blog by becoming a sponsor. Any amount is appreciated!