PHP 键名数组
我有一个数组 $data
fruit => apple,
seat => sofa,
等。我想循环遍历,使每个键变成 type_key[0]['value'] 所以例如
type_fruit[0]['value'] => apple,
type_seat[0]['value'] => sofa,
我认为会做到这一点,即
foreach ($data as $key => $value)
{
# Create a new, renamed, key.
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
# Destroy the old key/value pair
unset($array[$key]);
}
print_r($array);
不起作用。我怎样才能让它发挥作用?
另外,我希望键(而不是值)中的所有内容都是小写:是否也有一种简单的方法可以做到这一点?谢谢。
I have an array $data
fruit => apple,
seat => sofa,
etc. I want to loop through so that each key becomes type_key[0]['value'] so eg
type_fruit[0]['value'] => apple,
type_seat[0]['value'] => sofa,
and what I thought would do this, namely
foreach ($data as $key => $value)
{
# Create a new, renamed, key.
$array[str_replace("/(.+)/", "type_$1[0]['value']", $key)] = $value;
# Destroy the old key/value pair
unset($array[$key]);
}
print_r($array);
Doesn't work. How can I make it work?
Also, I want everything to be in the keys (not the values) to be lowercase: is there an easy way of doing this too? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的意思是要将键放入单独的数组中吗?或者您的意思是只更改同一数组中的键?
如果您希望键是单独的变量,请执行以下操作:
现在您将拥有 $type_fruit 和 $type_sofa。您可以在 $type_fruit[0]['value'] 中找到您的值,因为我们在其中放置了一个额外的嵌套数组。
Do you mean you want to make the keys into separate arrays? Or did you mean to just change the keys in the same array?
if you want your keys to be separate variables, then do this:
Now you will have $type_fruit and $type_sofa. You can find your values as $type_fruit[0]['value'], since we put an extra nested array in there.
你的要求听起来……很可疑。也许你的意思是这样的:
Your requirements sound... suspect. Perhaps you meant something like the following:
首先,我不会改变输入数组,而是创建一个新的数组,除非您的内存限制遇到严重的问题。
然后,您不能简单地替换键来向数组添加更深的嵌套级别。
$x[ 'abc[def]' ]
仍然只引用顶级元素,因为abc[def]
被解析为一个字符串,但您想要$x['abc']['def']
。First I wouldn't alter the input-array but create a new one unless you're in serious, serious trouble with your memory limit.
And then you can't simply replace the key to add a deeper nested level to an array.
$x[ 'abc[def]' ]
is still only referencing a top-level element, sinceabc[def]
is parsed as one string, but you want$x['abc']['def']
.对于初学者来说
应该是
for starters
should be