52 votes

Utilisation d'un chemin de chaîne pour définir les données d'un tableau imbriqué

J'ai un cas d'utilisation inhabituel pour lequel j'essaie de coder. Le but est le suivant : je souhaite que le client puisse fournir une chaîne, telle que :

 "cars.honda.civic = On"

En utilisant cette chaîne, mon code définira une valeur comme suit :

 $data['cars']['honda']['civic'] = 'On';

Il est assez facile de symboliser l'entrée du client en tant que telle :

 $token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);

Mais maintenant, comment utiliser $ exploded path pour définir le tableau sans faire quelque chose de méchant comme un eval?

77voto

alexisdm Points 16064

Utilisez l'opérateur de référence pour obtenir les tableaux existants successifs :

 $temp = &$data;
foreach($exploded as $key) {
    $temp = &$temp[$key];
}
$temp = $value;
unset($temp);

17voto

Ugo Méda Points 1194

D' après la réponse d'alexisdm :

 /**
 * Sets a value in a nested array based on path
 * See https://stackoverflow.com/a/9628276/419887
 *
 * @param array $array The array to modify
 * @param string $path The path in the array
 * @param mixed $value The value to set
 * @param string $delimiter The separator for the path
 * @return The previous value
 */
function set_nested_array_value(&$array, $path, &$value, $delimiter = '/') {
    $pathParts = explode($delimiter, $path);

    $current = &$array;
    foreach($pathParts as $key) {
        $current = &$current[$key];
    }

    $backup = $current;
    $current = $value;

    return $backup;
}

10voto

volocuga Points 296

Code bien testé et 100% fonctionnel. Définir, obtenir, désactiver les valeurs d'un tableau à l'aide de "parents". Les parents peuvent être soit array('path', 'to', 'value') soit une chaîne path.to.value . Basé sur le code de Drupal

  /**
 * @param array $array
 * @param array|string $parents
 * @param string $glue
 * @return mixed
 */
function array_get_value(array &$array, $parents, $glue = '.')
{
    if (!is_array($parents)) {
        $parents = explode($glue, $parents);
    }

    $ref = &$array;

    foreach ((array) $parents as $parent) {
        if (is_array($ref) && array_key_exists($parent, $ref)) {
            $ref = &$ref[$parent];
        } else {
            return null;
        }
    }
    return $ref;
}

/**
 * @param array $array
 * @param array|string $parents
 * @param mixed $value
 * @param string $glue
 */
function array_set_value(array &$array, $parents, $value, $glue = '.')
{
    if (!is_array($parents)) {
        $parents = explode($glue, (string) $parents);
    }

    $ref = &$array;

    foreach ($parents as $parent) {
        if (isset($ref) && !is_array($ref)) {
            $ref = array();
        }

        $ref = &$ref[$parent];
    }

    $ref = $value;
}

/**
 * @param array $array
 * @param array|string $parents
 * @param string $glue
 */
function array_unset_value(&$array, $parents, $glue = '.')
{
    if (!is_array($parents)) {
        $parents = explode($glue, $parents);
    }

    $key = array_shift($parents);

    if (empty($parents)) {
        unset($array[$key]);
    } else {
        array_unset_value($array[$key], $parents);
    }
}

6voto

deceze Points 200115
$data = $value;
foreach (array_reverse($exploded_path) as $key) {
    $data = array($key => $data);
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X