本文介绍了使用字符串路径设置嵌套数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个不寻常的用例.目标是这样的:我希望客户能够提供一个字符串,例如:
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);
但是现在,我如何使用 $exploded path 来设置数组而不做一些像 eval 这样令人讨厌的事情?
But now, how do I use $exploded path to set the array without doing something nasty like an eval?
推荐答案
使用引用运算符获取连续存在的数组:
Use the reference operator to get the successive existing arrays:
$temp = &$data;
foreach($exploded as $key) {
$temp = &$temp[$key];
}
$temp = $value;
unset($temp);
这篇关于使用字符串路径设置嵌套数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!