我有一个不寻常的用例,我正在尝试编写代码.目标是:我希望客户能够提供字符串,例如:
"cars.honda.civic = On"
Run Code Online (Sandbox Code Playgroud)
使用此字符串,我的代码将设置如下值:
$data['cars']['honda']['civic'] = 'On';
Run Code Online (Sandbox Code Playgroud)
很容易将客户输入标记为:
$token = explode("=",$input);
$value = trim($token[1]);
$path = trim($token[0]);
$exploded_path = explode(".",$path);
Run Code Online (Sandbox Code Playgroud)
但是现在,我如何使用$爆炸路径设置数组而不做像eval那样讨厌的东西?
我想剖析这样的数组:
[
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
]
Run Code Online (Sandbox Code Playgroud)
改成这样的格式:
{
"ID" : 1,
"UUID" : 1,
"pushNotifications" :
{
"sent" : 1,
"tapped" : 1
},
"campaigns" :
{
"boundDate" : 1,
"endDate" : 1,
"pushMessages" :
{
"endDate" : 1
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我能够以类似键路径的方式在关联数组上设置一个值,那就太好了:
//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;
//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;
Run Code Online (Sandbox Code Playgroud)
如何在 PHP 中做到这一点?