I'm trying to organize my mysql table into a multidimension php tree array.
For example, I'm trying to organize my products in a hierarchy for easy selection to narrow down the result the narrower they go in the result.
I am returned mysql rows like this:
Array
(
[1] => Amazon
[2] => Kindle Fire
[3] =>
[4] =>
[5] =>
[6] =>
[7] =>
[8] =>
[9] => 1
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 2
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 3
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 4
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => WiFi
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 5
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 6
)
Array
(
[1] => Amazon
[2] => Kindle Fire HD
[3] => 4G LTE
[4] => 8.9"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 7
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 16GB
[7] =>
[8] =>
[9] => 8
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 32GB
[7] =>
[8] =>
[9] => 9
)
Array
(
[1] => Amazon
[2] => Kindle Fire HDX
[3] => Wifi
[4] => 7"
[5] =>
[6] => 64GB
[7] =>
[8] =>
[9] => 10
)
...etc
Note the last array value is the Product ID.
And I'm looking for help writing a recursive function that will result in an array that looks like:
Array(
'Amazon' => Array(
'Kindle Fire' => 1,
'Kindle Fire HD' => Array(
'WiFi' => Array(
'7"' => Array(
'16GB' => 2,
'32GB' => 3
)
'8.9"' => Array(
'16GB' => 4,
'32GB' => 5
)
)
)
)
)
I've tried something like:
while($row = mysqli_fetch_row($res)) {
$id = $row[0];
unset($row[0]);
unset($row[count($row)]);
$row[] = $id; // Moves id to last array value
for($i = 1; $i < count($row); $i++) {
if($i == 1) {
if(!array_key_exists($row[$i], $data)) {
// Insert key
$data[$row[$i]] = array();
}
}
else {
$level = $data[$row[$i-1]];
if(array_key_exists($row[$i], $level)) {
// Key exists
}
else {
// Insert key
}
}
}
}