Reputation: 433
I have a theoretical question that I cannot seem to figure out. Imagine I have the following data in a database:
Main Sub1 Sub2
a x y
x t u
u f g
I want to make a multidimensional array in PHP/mYSQL by essentially asking "what is each 'main' component made of?"
The result would be something like this:
Array
(
[0] => a
(
[0] => x
(
[0] => t
[1] => u
)
(
[0] => f
[1] => g
)
[1] => y
)
)
My efforts result in lots of arrays, instead of a multidimensional array.
Upvotes: 2
Views: 110
Reputation: 173562
You can use references to solve this, although the results will get a bit messy:
$res = [];
foreach ($rows as $row) {
// check if we have each sub component
if (!isset($res[$row['sub1']])) {
$res[$row['sub1']] = $row['sub1'];
}
if (!isset($res[$row['sub2']])) {
$res[$row['sub2']] = $row['sub2'];
}
// build new component with references to the sub components
$res[$row['main']] = [&$res[$row['sub1']], &$res[$row['sub2']]];
}
print_r($res);
Array
(
[x] => Array
(
[0] => t
[1] => Array
(
[0] => f
[1] => g
)
)
[y] => y
[a] => Array
(
[0] => Array
(
[0] => t
[1] => Array
(
[0] => f
[1] => g
)
)
[1] => y
)
[t] => t
[u] => Array
(
[0] => f
[1] => g
)
[f] => f
[g] => g
)
You can clean up the results by filtering out only the arrays:
print_r(array_filter($res, 'is_array'));
Array
(
[x] => Array
(
[0] => t
[1] => Array
(
[0] => f
[1] => g
)
)
[a] => Array
(
[0] => Array
(
[0] => t
[1] => Array
(
[0] => f
[1] => g
)
)
[1] => y
)
[u] => Array
(
[0] => f
[1] => g
)
)
Upvotes: 1