Creazione di un'istanza di una coppia di valore chiave PHP senza un array
-
22-09-2019 - |
Domanda
Sto scrivendo una funzione ricorsiva per costruire un array multidimensionale. Fondamentalmente, il problema è il seguente:
function build($term){
$children = array();
foreach ( $term->children() as $child ) {
$children[] = build($child);
}
if(!count($children)){
return $term->text();
} else {
return $term->text() => $children; //obviously, this doesn't work
}
}
Pensieri? So che potrei riscrivere la struttura della funzione per farlo funzionare, ma sembra che dovrebbe essere inutile.
Soluzione
Un array è l'unico contenitore per coppia di valore chiave che PHP ha da offrire. Quindi devi usare un array se si desidera la tua funzione (possa essere ricorsivo o meno) restituire una coppia di valore chiave.
return array($term->text() => $children);
Altri suggerimenti
function build($term){
$children = array();
foreach ( $term->children() as $child ) {
$children += build($child);
}
if(!count($children)){
return $term->text();
} else {
return array($term->text() => $children); //obviously, this doesn't work
}
}
Da quello che capisco della domanda questo è come dovrebbe essere.
Aggiungere la ricorsione e restituire un array.
Modifica: a parte potresti essere meglio restituire un array anche se il conteggio ($ bambini) == 0, questo otterrebbe tutti i tuoi tipi in linea. altrimenti potresti ottenere tutti i tipi di errori lungo la linea:
if(!count($children)){
return array($term->text() => null);
Potresti restituirlo in questo modo:
return array($term->text() => $children);
Anche se non è quello che hai chiesto. Penso che non puoi farlo senza riscrivere parti della tua funzione, in un modo o nell'altro.