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

2022-08-30 10:29:41

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

"cars.honda.civic = On"

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

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

将客户输入标记化非常简单:

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

但是现在,我如何使用$exploded路径来设置数组,而不做一些令人讨厌的事情,比如eval?


答案 1

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

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

答案 2

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