I’m trying to recursively create a php array for my phone database.
The database has many different phones and I want to categorize them like this:
iPhone 14 Pro:
128gb:
Black: 2
White: 1
256gb:
Red: 3
Black: 1
iPhone 13 Pro:
................
The database is formatted like this:
model: iPhone 14 Pro, storage: 128gb, color: Black
model: iPhone 14 Pro, storage: 256gb, color: Blue
...........
And so on
I tried using some nested loops with too many foreach statements and it didn’t work at all.
I think I was using the array_push method incorrectly because I never got the correct result
My hope is that someone here knows how to recursively create this array by looping through the full dataset.
Thank you in advance!
2
Answers
Assuming the defining factors, like
model
,storage
andcolor
are columns in the database, you could create a simple function like the followingYou also have the ability to simplify the functionality/code using inbuilt PHP functions like
array_reduce( )
:Which provides the desired output.
Example
Not sure how you data is structured, but something like this might work:
The above would create an array like this: