在 php 中,我如何将类似的数组(“一”,“二”,“三”)制作成 $somearray[“一”][“二”][“三”]?
我想采用一个数组,例如:
array("one", "two", "three");
并将其放入数组的数组中,例如:
$someArray["one"]["two"]["three"];
数组的数组($someArray
)必须通过某种循环创建作为初始数组是由 explode()
创建的,所以我不知道 $someArray
有多深。
我希望这很清楚,感谢大家的宝贵时间!
我自己现在正在阅读它,array_map()
可以用于此吗?
I would like to take an array, say:
array("one", "two", "three");
and make it into an array of arrays, like:
$someArray["one"]["two"]["three"];
The array of arrays ($someArray
) would have to be created by some sort of loop as the initial array is created by an explode()
so i don't know how deep $someArray
would be.
I hope this is clear, thanks all for your time!
I am reading up on it at the moment myself, would array_map()
work for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样做:
最后的
$ref
是对$arr['one']['two']['third']
的引用(如果存在)。如果将break
替换为$ref[$key] = array()
,您将使用该结构构建一个数组。You can do this:
At the end
$ref
is a reference to$arr['one']['two']['three']
if it exists. And if you replacebreak
by$ref[$key] = array()
you will build an array with that structure instead.您应该使用 array_reduce。
解决方案非常简单。
要做到这一点,请反转数组,然后再应用归约。
编辑扩展和解释的版本:
在 php 中,我们没有自动深入数组的函数,但我们没有这样做。
如果从底部开始,我们将能够将一个数组包含在前一个数组中
通过简单的分配。
顺便说一句,我更喜欢较短的形式。我认为这是一个函数式习惯用法,不需要向经验丰富的中级开发人员(具有一些函数式背景)进一步解释。第二个添加了很多噪音,适合学习,但来源
分散注意力到生产代码中(显然我指的是只有一个 return 语句的函数)。
You should use array_reduce.
The solution is quite simple.
To do the trick, reverse the array and only then apply the reduction.
EDIT an expanded and explained version:
In php we don't have a function to go deep into an array automatically but we haven't to.
If you start from the bottom, we will be able to enclose an array into the previous one
with a simple assignation.
By the way I prefer the shorter form. I think it is a functional idiom and doesn't need further explanation to a middle experienced developer (with a bit of functional background). The second one add a lot of noise that, it is suitable to learn but source
of distraction into production code (obviously I'm referring to function with just a return statement).
我不确定你为什么想要这个。
但是,您想要的基础是这样的,
这应该是您想要的 $array;
这是未经测试的,但我认为如果它不只是告诉我它在做什么,那应该可行,我会看看
i'm not sure why you would want this.
But but the basis of what your wanting would be like this
This should then right what you want to $array;
This is untested but i think that should work if it does not just tell me what its doing and i will have a look
当你打印 $arrNew 时,它会打印这个..
)
When you print $arrNew, It will print this..
)