php - 使用字符串路徑設置嵌套數組數據




arrays token (5)

你能不能這樣做

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

我有一個不尋常的用例,我正在嘗試編寫代碼。 目標是:我希望客戶能夠提供字符串,例如:

"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這樣令人討厭的事情?


使用引用運算符獲取連續的現有數組:

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

基於alexisdm的回复 :

/**
 * Sets a value in a nested array based on path
 * See https://.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;
}

您需要使用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'

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




token