How to build a nested structure from a "flat"?

There is a selection of database types:

product: 20
component: 31
-----------------
product: 20
component: 45
-----------------
product: 20
component: 51
-----------------
product: 45
component: 55
-----------------
product: 45
component: 61
...


Where component is the same product, and that product, just this table displays what product what components (products) is.

Must of this flat structure to collect an array of the form:
$arr = [
 20 => [
 31 => [],
 45 => [
 24 => [ // ... ],
 48 => [ // ... ]
],
 51 => []
],
 45 => [
 55 => [ // ... ]
 61 => [ // ...]
]
];


Ie, what would each product had the products, which in turn also consists of the products, and so on, nesting is not limited, as to fasten recursion?
April 4th 20 at 00:44
1 answer
April 4th 20 at 00:46
Solution
Something like that
function fill($tmp, $value) {
 $ans = array();
 if (array_key_exists($value, $tmp)) {
 foreach ($tmp[$value] as $val) {
 $ans[$val] = fill($tmp, $val);
}
}
 return $ans;
}

$input = array(
array(
 'product' => 20,
 'component' => 31,
),
array(
 'product' => 20,
 'component' => 45,
),
array(
 'product' => 20,
 'component' => 51,
),
array(
 'product' => 45,
 'component' => 55,
),
array(
 'product' => 45,
 'component' => 61,
)
);

$tmp = array();
foreach ($input as $item) {
 if (array_key_exists($item['product'], $tmp)) {
 array_push($tmp[$item['product']], $item['component']);
 } else {
 $tmp[$item['product']] = array($item['component']);
}
}

$ans = array();
foreach ($tmp as $key => $val) {
 $ans[$key] = fill($tmp, $key);
}

print_r($ans);

Find more questions by tags PHP