Set nidificati, array php e trasformazione
-
20-08-2019 - |
Domanda
Ho bisogno di trasformare la mia struttura di insiemi nidificati (mysql) in json per questo spazio 1) http://blog.thejit.org/wp -CONTENUTO / JIT-1.0a / examples / spacetree.html
Ho trovato questa funzione per creare un array da set nidificati: 2) http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php
Posso anche convertire l'array php in json con la funzione PHP json_encode
Il mio problema: la funzione nestify (dal secondo link) non mi dà esattamente ciò di cui ho bisogno. Ho bisogno di qualcosa del genere: http://pastebin.com/m68752352
Puoi aiutarmi a cambiare la funzione " nestify " quindi mi dà l'array corretto?
Ecco questa funzione ancora una volta:
function nestify( $arrs, $depth_key = 'depth' )
{
$nested = array();
$depths = array();
foreach( $arrs as $key => $arr ) {
if( $arr[$depth_key] == 0 ) {
$nested[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
else {
$parent =& $nested;
for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
$parent =& $parent[$depths[$i]];
}
$parent[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
}
return $nested;
}
Soluzione
Il seguente frammento dovrebbe fare il trucco, adattato da un po 'di codice PHP Doctrine che ho trovato sul web:
function toHierarchy($collection)
{
// Trees mapped
$trees = array();
$l = 0;
if (count($collection) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($collection as $node) {
$item = $node;
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root node
$i = count($trees);
$trees[$i] = $item;
$stack[] = & $trees[$i];
} else {
// Add node to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = & $stack[$l - 1]['children'][$i];
}
}
}
return $trees;
}