Skip to content
Advertisement

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

I am getting an array from an API that varies in number of levels but follows the same basic structure – here is a truncated sample as this particular repsonse is 25K lines:

JavaScript

I need to traverse the json, and where 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”) and the data that immediately follows the “value”/”id” in [Rows][Row][Rows][Row][ColData] (in this snippet starting with “ColData”: [{“value”: “2022-01-24″…)

[Rows][Row][Rows][Row][ColData] will have one to a few hundred subarrays. I can extract the data from the subarrays once they are found – it’s just managing the varying depths of the array that is warping my brain.

[Rows][Row][Rows][Summary] can be discarded as well.

I have tried multiple foreach loops – but by time I get 5 or 6 levels deep it gets very confusing. The number of Header sections varies depending on the report type. The [Rows][Row] nesting is multiple layers deep… I’m sure there has to be a better way than nesting foreach loops…

Advertisement

Answer

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement