使用字符串路径设置嵌套数组数据 [英] Using a string path to set nested array data

查看:110
本文介绍了使用字符串路径设置嵌套数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我试图code一个不寻常的用例。的目标是:我想的顾客能够提供一个串,诸如:

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"

使用这个字符串,我的code将如下设置一个值:

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

但现在,我怎么使用$爆炸路径设置数组没有做一些讨厌像一个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);

这篇关于使用字符串路径设置嵌套数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆