将点分隔成数组键的字符串转换为数组键
我有一个字符串(例如 one.two. Three
或 month.2
),我需要将此字符串爆炸点字符转换为数组键。
所以我有 month.2
并且我需要代码线将此字符串转换为 $lang['month'][2]
我一直在寻找该解决方案,但我不是能找到吗,我被屏蔽了。
我终于找到了这个:
<?php
$lang['one']['two']['three'] = 'well done';
$str = 'one.two.three';
$list = explode('.', $str);
$result = '$lang';
foreach ($list as $item)
{
$result .= '["'.$item.'"]';
}
var_dump(eval("return " . $result.';'));
?>
I have an string (like one.two.three
or month.2
) and I need to translate this string exploding point character into array keys.
So I have month.2
and I need the codeline to translate this string into $lang['month'][2]
I was looking for that solution but I am not able to find it, I am blocked.
I finally found this:
<?php
$lang['one']['two']['three'] = 'well done';
$str = 'one.two.three';
$list = explode('.', $str);
$result = '$lang';
foreach ($list as $item)
{
$result .= '["'.$item.'"]';
}
var_dump(eval("return " . $result.';'));
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先分解它:
然后将其重写为嵌套数组:
最后合并:
编辑:如果您想要读取数组,那么 bazmegakapa 的答案就是您正在寻找的。
Start by exploding it:
Then rewrite it as a nested array:
And finally merge:
Edit: in case you're seeking to read the array instead, then bazmegakapa's answer is what you're looking for.
我写了一个小递归函数来处理这个问题。首先,分解字符串,并将数组(在您的示例中为
$lang
,在我的示例中为$a
)和此分解数组传递给GetVal()
。它会尽力将所需的值返回到$x
中。I wrote a little recursive function to handle this. First you explode the string, and pass the array (
$lang
in your example,$a
in mine) and this exploded array toGetVal()
. It will do its best to return the needed value into$x
.这是对explode函数使用的澄清:
这段代码爆炸为:
not as Array[hello][world][its][a].......
Its a clarification for the use of explode function:
this code explodes as:
not as Array[hello][world][its][a].......