How can I transform array#1 into the array#2 structure using php ?
The first Array is the results of a database query on a list of Organisms, each organism is classified with it's Order, Family, Genus, Species. Hierarchically Species are the child classifications of various Genus, and Genus classifications are child classifications of various Families etc .
In namespace terms you could read it like so:
item at index[ 0] ---> Hemiptera.Miridae.Kanakamiris
item at index[ 1] ---> Hemiptera.Miridae.Neophloeobia.incisa
There is a kind of parent/child relationship between the keys of array#1 which is as follows:
- 'Rank_Order' value is the parent of the 'Rank_Family' value
- 'Rank_Family' value is the parent of the 'Rank_Genus' value
- 'Rank_Genus' value is the parent of the 'Rank_Species' value
array#1:
Array
(
[0] => Array
(
['Rank_Order'] => 'Hemiptera'
['Rank_Family'] => 'Miridae'
['Rank_Genus'] => 'Kanakamiris'
['Rank_Species'] => ''
)
[1] => Array
(
['Rank_Order'] => 'Hemiptera'
['Rank_Family'] => 'Miridae'
['Rank_Genus'] => 'Neophloeobia'
['Rank_Species'] => 'incisa'
)
[2] => Array
(
['Rank_Order'] => 'Hemiptera'
['Rank_Family'] => 'Noridae'
['Rank_Genus'] => 'Canelbia'
['Rank_Species'] => 'Arissa'
)
)
The following array is the array structure i need: array#2:
Array(
[name] => 'Hemiptera'
[children] => Array(
[0] => Array(
[name] => 'Miridae'
[children] => Array(
[0] => Array(
[name] => 'Kanakamiris'
[children] => Array(
)
)
[1] => Array(
[name] => 'Neophloeobia'
[children] => Array(
[0] => Array(
[name] => 'incisa'
[children] => Array(
)
)
)
)
)
)
[1] => Array(
[name] => 'Noridae'
[children] => Array(
[0] => Array(
[name] => 'Canelbia'
[children] => Array(
[0] => Array(
[name] => 'Arissa'
[children] => Array(
)
)
)
)
)
)
)
)
I see similar questions asked in stack overflow, though have not been able to use them in my case. eg. php-reorder-array-to-reflect-parent-id-hierarchy