Using a string path to set nested array data

2019-01-02 17:41发布

I have an unusual use-case I'm trying to code for. The goal is this: I want the customer to be able to provide a string, such as:

"cars.honda.civic = On"

Using this string, my code will set a value as follows:

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

It's easy enough to tokenize the customer input as such:

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

But now, how do I use $exploded path to set the array without doing something nasty like an eval?

标签: php arrays token
8条回答
临风纵饮
2楼-- · 2019-01-02 18:20

Based on Ugo Méda's response :

This version

  • allows you to use it solely as a getter (leave the source array untouched)
  • fixes the fatal error issue if a non-array value is encountered (Cannot create references to/from string offsets nor overloaded objects)

no fatal error example

$a = ['foo'=>'not an array'];
arrayPath($a, ['foo','bar'], 'new value');

$a is now

array(
    'foo' => array(
        'bar' => 'new value',
    ),
)

Use as a getter

$val = arrayPath($a, ['foo','bar']);  // returns 'new value' / $a remains the same

Set value to null

$v = null; // assign null to variable in order to pass by reference
$prevVal = arrayPath($a, ['foo','bar'], $v);

$prevVal is "new value"
$a is now

array(
    'foo' => array(
        'bar' => null,
    ),
)

 

/**
 * set/return a nested array value
 *
 * @param array $array the array to modify
 * @param array $path  the path to the value
 * @param mixed $value (optional) value to set
 *
 * @return mixed previous value
 */
function arrayPath(&$array, $path = array(), &$value = null)
{
    $args = func_get_args();
    $ref = &$array;
    foreach ($path as $key) {
        if (!is_array($ref)) {
            $ref = array();
        }
        $ref = &$ref[$key];
    }
    $prev = $ref;
    if (array_key_exists(2, $args)) {
        // value param was passed -> we're setting
        $ref = $value;  // set the value
    }
    return $prev;
}
查看更多
冷夜・残月
3楼-- · 2019-01-02 18:21

Based on alexisdm's response :

/**
 * 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;
}
查看更多
唯独是你
4楼-- · 2019-01-02 18:29

Well tested and 100% working code. Set, get, unset values from an array using "parents". The parents can be either array('path', 'to', 'value') or a string path.to.value. Based on Drupal's code

 /**
 * @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);
    }
}
查看更多
临风纵饮
5楼-- · 2019-01-02 18:32

Can't you just do this

$exp = explode(".",$path);
$array[$exp[0]][$exp[1]][$exp[2]] = $value
查看更多
余欢
6楼-- · 2019-01-02 18:33

You can use this function:

Arr::handleNestedElement($data, $path, $value);

from this library. It accepts keys both as string with dot delimeter or array.

查看更多
伤终究还是伤i
7楼-- · 2019-01-02 18:38

Use the reference operator to get the successive existing arrays:

$temp = &$data;
foreach($exploded as $key) {
    $temp = &$temp[$key];
}
$temp = $value;
unset($temp);
查看更多
登录 后发表回答