json - Better way to iterate multidimensional array of unknown complexity from API than a dozen foreach loops in PHP

one text

Solution:

This is what I've come up with. Kindly modify it to meet your need.

$array = json_decode($json, true);

function  traverse_some_array($array){
    $result = [];
    foreach($array['Rows']['Row'] ?? [] as $row){
        if( !empty($row['Header']['ColData']) ){
            foreach($row['Header']['ColData'] as $coldata){
                if( isset($coldata['value'], $coldata['id']) ){
                    // there is data in both [Header][ColData][value] AND [Header][ColData][id]

                    // extract the value, id (in this snippet "value": "40000 Sales Income", "id": "31")
                    $extract_data = [
                        'value' => $coldata['value'],
                        'id'    => $coldata['id']
                    ];

                    // the data that immediately follows the "value"/"id" in [Rows][Row][Rows][Row][ColData]
                    $immediate_coldata = $row['Rows']['Row'] ?? [];

                    // you can do what ever you want with the results, eg return it or push it to a result array
                    $result[] = [
                        'extract_data' => $extract_data,
                        'immediate_coldata' => $immediate_coldata
                    ];
                }else{
                    // continue traversing the array
                    $result = array_merge($result,  traverse_some_array($row));
                }
            }
        }
    }
    return $result;
}

print_r(traverse_some_array($array));

Source