2015-05-21 16 views

risposta

5

Ecco uno che solo altera la matrice originale invece di creare una nuova variabile utilizzando array_walk:

$a = ["I", "need", "this", "to", "be", "nested"]; 
array_walk(array_reverse($a), function ($v, $k) use (&$a) { 
    $a = $k ? [$v => $a] : [$v]; 
}); 

Se $a è vuota, questo dovrebbe lasciare come vuoto . Tuttavia, presuppone che l'array di input abbia chiavi a partire da 0.

+0

Questo è perfetto! Mentre non ho chiesto un cambiamento sul posto, questa sembra essere la versione più compatta, che stavo davvero cercando. –

+0

@DeadManWalker, in realtà questa non è la versione più compatta. Ecco uno spelling della prima funzione da [la mia risposta] (http://stackoverflow.com/a/30365085/2266855): 'function mn ($ a) {return count ($ a) <2? $ a: [array_shift ($ a) => mn ($ a)]; } '. Anche la mia funzione è più efficiente. – dened

23

Ecco una possibile implementazione:

<?php 

function make_nested($array) { 
    if (count($array) < 2) 
     return $array; 
    $key = array_shift($array); 
    return array($key => make_nested($array)); 
} 

print_r(make_nested(array("I", "need", "this", "to", "be", "nested"))); 

Se non vi piace la ricorsione, qui è una versione iterativa:

function make_nested($array) { 
    if (!$array) 
     return array(); 
    $result = array(array_pop($array)); 
    while ($array) 
     $result = array(array_pop($array) => $result); 
    return $result; 
} 
4

userei a for -loop per questo :)

$array = array("I", "need", "this", "to", "be", "nested"); 

$newArray[$array[count($array)-2]] = array_pop($array); 

for($i = count($array) - 2; $i > -1; $i--) { 
    $newArray[$array[$i]] = $newArray; 
    unset($newArray[$array[$i+1]]); 
} 

print_r($newArray); 
1

Questo sembra funzionare.

$a = array("I", "need", "this", "this", "to", "be", "nested"); 
$r = array($a[sizeof($a) - 1]); 
for ($i=sizeof($a)-2; $i >= 0; $i--) { 
    $r = array($a[$i] => $r); 
} 
echo($ar == $r); 
3

Run The Code

<?php 

    // nested_array(array, start_index, length) 
    function nested_array($arr, $i, $size) 
    { 
     if ($i == ($size-1)) 
     { 
      return array($arr[$i] => array()); 
     } 
     return array($arr[$i] => nested_array($arr,($i+1),$size)); 
    } 

    print_r(nested_array(array("I", "need", "this", "to", "be", "nested"),0,6)); 

?> 
+4

L'OP voleva che il loro array più interno assomigliasse a 'array (" be "=> array (" nested "))', il codice restituisce 'Array ([be] => nested) '. Penserei che un array vuoto avrebbe più senso, a proposito: '[" be "=> [" nested "=> []]]'. – Kobi

+0

@Kobi note fixed –

17

Utilizzando array_reduce:

$a = ["I", "need", "this", "to", "be", "nested"]; 

$result = array_reduce(array_reverse($a), function($prevArray, $key){ 
    return $prevArray ? [$key => $prevArray] : [$key]; 
}, null); 

Nota che stiamo usando array_reverse perché non un sinistro a ridurre c'è.

esempio di funzionamento: http://ideone.com/N61VtE

Problemi correlati