将分隔字符串转换为数组键路径并赋值
我有一个像这样的字符串:
$string = 'one/two/third/four';
我将其转换为数组:
$keys =explode('/', $string) ;
该数组可以有任意数量的元素,例如 1、2、5 等。
如何为多维数组分配某个值,但使用上面创建的 $keys
确定插入的位置?
就像:
$arr['one']['two']['third']['four'] = 'value';
抱歉,如果问题令人困惑,但我不知道如何为了更好地解释它
I have a string like this:
$string = 'one/two/three/four';
which I turn it into a array:
$keys = explode('/', $string);
This array can have any number of elements, like 1, 2, 5 etc.
How can I assign a certain value to a multidimensional array, but use the $keys
I created above to identify the position where to insert?
Like:
$arr['one']['two']['three']['four'] = 'value';
Sorry if the question is confusing, but I don't know how to explain it better
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这有点不简单,因为你想要嵌套,但它应该是这样的:
This is kind of non-trivial because you want to nest, but it should go something like:
这是做什么的:
$ref
来跟踪对$arr
当前维度的引用。$keys
,引用当前引用的$key
元素。What this is doing:
$ref
, to keep track of a reference to the current dimension of$arr
.$keys
one at a time, referencing the$key
element of the current reference.您需要首先确保键存在,然后分配值。像这样的东西应该有效(未经测试):
You'll need to first make sure the key's exist, then assign the value. Something like this should work (untested):
这很老套,但是:
it's corny but:
这将为您提供数组中的值。
this will give u your value in array.