使用字符串路径设置嵌套数组数据

时间:2012-03-09 02:32:10

标签: php arrays token

我有一个不寻常的用例,我正在尝试编写代码。目标是:我希望客户能够提供字符串,例如:

"cars.honda.civic = On"

使用此字符串,我的代码将设置如下值:

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

很容易将客户输入标记为:

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

但是现在,我如何使用$爆炸路径设置数组而不做像eval这样令人讨厌的事情?

8 个答案:

答案 0 :(得分:62)

使用引用运算符获取连续的现有数组:

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

答案 1 :(得分:15)

基于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;
}

答案 2 :(得分:6)

经过良好测试和100%正常工作的代码。使用“parents”设置,获取,取消设置数组中的值。父母可以是array('path', 'to', 'value')或字符串path.to.value。基于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);
    }
}

答案 3 :(得分:4)

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

答案 4 :(得分:4)

基于Ugo Méda's response

此版本

  • 允许您仅将其用作吸气剂(保持源阵列不受影响)
  • 修复了遇到非数组值(Cannot create references to/from string offsets nor overloaded objects
  • 时的致命错误问题

没有致命错误示例

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

$a现在

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

用作吸气剂

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

将值设置为null

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

$prevVal是“新价值”
$a现在是

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;
}

答案 5 :(得分:0)

您需要使用Symfony PropertyPath

<?php
// ...
$person = array();

$accessor->setValue($person, '[first_name]', 'Wouter');

var_dump($accessor->getValue($person, '[first_name]')); // 'Wouter'
// or
// var_dump($person['first_name']); // 'Wouter'

答案 6 :(得分:0)

您可以使用此功能:

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

来自this library。它既接受键,也接受点字符串或带点分隔符的数组。

答案 7 :(得分:-5)

你不能这样做吗

$exp = explode(".",$path);
$array[$exp[0]][$exp[1]][$exp[2]] = $value