2010-06-29 9 views
4

Désolé pour le titre terrible, meilleur que je pouvais penser à l'époque! Dites que j'ai un tableau 'chemin' comme ça;Définir un tableau multidimensionnel par chemin clé à partir des valeurs de tableau?

array('this', 'is', 'the', 'path')

Quelle serait la méthode la plus efficace pour se retrouver avec le tableau ci-dessous?

array(
    'this' => array(
     'is' => array(
      'the' => array(
       'path' => array() 
      ) 
     ) 
    ) 
) 
+0

Voulez-vous obtenir une valeur, définissez une valeur ou construire une telle structure par ce chemin? – flori

Répondre

6

Juste itérer dessus avec quelque chose comme array_shift ou array_pop:

$inarray = array('this', 'is', 'the', 'path',); 
$tree = array(); 
while (count($inarray)) { 
    $tree = array(array_pop($inarray) => $tree,); 
} 

Non testé, mais c'est la structure de base de celui-ci. La récursivité convient également bien à la tâche. Sinon, si vous ne voulez pas modifier le tableau initial:

$inarray = array('this', 'is', 'the', 'path',); 
$result = array(); 
foreach (array_reverse($inarray) as $key) 
    $result = array($key => $result,); 
0

pas vraiment élégant. mais il fonctionne

$ start = array ('ce', 'est', 'la', 'chemin')

$ result [start $ [0]] [$ start [1]] [$ start [2]] [$ start [3]] = array();

+1

Trouble is, qui ne fonctionne qu'avec un nombre prédéfini - que se passe-t-il si je ne connais pas le nombre de nœuds présents dans le chemin? – TheDeadMedic

1
function buildArrayFromPath($path) { 
    $out = array(); 
    while($pop = array_pop($path)) $out = array($pop => $out); 
    return $out; 
} 
1

Une solution récursive:

function find_in_array(&$array, &$path, $_i=0) { 
    // sanity check 
    if (!(is_array($array) && is_array($path))) return false; 
    $c = count($path); if ($_i >= $c) return false; 

    $k = $path[$_i]; 
    if (array_key_exists($k, $array)) 
    return ($_i == $c-1) ? $array[$k] : find_in_array($array[$k], $path, $_i+1); 
    else 
    return false; 
} 

Paramètre $_i est à usage interne et ne doit pas être réglé lors de l'appel fonction.

7

J'utilise deux fonctions similaires pour obtenir et définir des valeurs par leur chemin dans un tableau:

function array_get($arr, $path) 
{ 
    if (!$path) 
     return null; 

    $segments = is_array($path) ? $path : explode('/', $path); 
    $cur =& $arr; 
    foreach ($segments as $segment) { 
     if (!isset($cur[$segment])) 
      return null; 

     $cur = $cur[$segment]; 
    } 

    return $cur; 
} 

function array_set(&$arr, $path, $value) 
{ 
    if (!$path) 
     return null; 

    $segments = is_array($path) ? $path : explode('/', $path); 
    $cur =& $arr; 
    foreach ($segments as $segment) { 
     if (!isset($cur[$segment])) 
      $cur[$segment] = array(); 
     $cur =& $cur[$segment]; 
    } 
    $cur = $value; 
} 

Ensuite, vous les utiliser comme ceci:

$value = array_get($arr, 'this/is/the/path'); 
$value = array_get($arr, array('this', 'is', 'the', 'path')); 
array_set($arr, 'here/is/another/path', 23); 
Questions connexes