I've spent hours trying to find the answer to this question, but I'm struggling. I'm reasonably familiar with PHP and the various in-built functions, and can build a complex foreach() loop to do this, but I thought I'd ask to see if anyone has a smarter solution to my problem.
I have the following simplified example array with three "rows" (the real array is usually a lot bigger and more complex, but the issue is the same).
$rows[] = [
"widget_id" => "widget1",
"size" => "large",
"item" => [
"item_id" => "item1",
"shape" => "circle",
"paint" => [
"paint_id" => "paint1",
"colour" => "red",
]
]
];
# Exactly the same as above, except the "paint" child array is different
$rows[] = [
"widget_id" => "widget1",
"size" => "large",
"item" => [
"item_id" => "item1",
"shape" => "circle",
"paint" => [
"paint_id" => "paint2",
"colour" => "green",
]
]
];
# Same children ("item" and "paint") as the first row, but different parents ("widget_id" is different)
$rows[] = [
"widget_id" => "widget2",
"size" => "medium",
"item" => [
"item_id" => "item1",
"shape" => "circle",
"paint" => [
"paint_id" => "paint1",
"colour" => "red",
]
]
];
What I'm trying to get to is the following output:
[[
"widget_id" => "widget1",
"size" => "large",
"item" => [
"item_id" => "item1",
"shape" => "circle",
"paint" => [[
"paint_id" => "paint1",
"colour" => "red",
],[
"paint_id" => "paint2",
"colour" => "green",
]]
]
],[
"widget_id" => "widget2",
"size" => "medium",
"item" => [
"item_id" => "item1",
"shape" => "circle",
"paint" => [
"paint_id" => "paint1",
"colour" => "red",
]
]
]]
Basically, when two rows share the same key and values, merge them. When the key is the same, but the value is different, keep both values and put them in a numerical array under the key (sort of like how array_merge_recursive
does it).
The challenge is that the values can themselves be arrays and there is an unknown number of levels. Is there a smart and effective way of doing this, or do I have to resort to a heavy duty foreach
loop?
Thank you for browsing, hope there are some people more clever than me reading this!