PHP 数组未设置字符串
我正在尝试取消设置一组具有相同前缀的数组键。我似乎无法让它发挥作用。
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
我怎样才能取消设置以查看 ['prefix_' . $key] 作为实际变量?谢谢
更新: $array 键将有两个同名的键。只有一个有前缀,大约有 5 个带有前缀键的键:
Array {
[name] => name
[prefix_name] => other name
}
我不想从数组中删除 [name] 只是 [prefix_name]。
I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这有效:
如果您在 http://writecodeonline.com/php/ 之类的网站复制/粘贴此代码,您可以亲眼看看它是否有效。
This works:
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
您不能使用 foreach,因为它只是集合的副本。您需要使用 for 或单独获取键,并将处理与要操作的数组分开。类似于:
您也已经在迭代集合以获得每个键。除非你有:(
每个键也有一个前面带有“prefix_”的匹配键)你会遇到麻烦。
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
You're also already iterating over the collection getting every key. Unless you had:
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
我不确定我是否理解您的问题,但如果您尝试取消设置具有特定前缀的所有键,您可以迭代数组并仅取消设置与前缀匹配的键。
像这样的东西:
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
您已经在遍历数组键了,所以如果您有
那么 $keys 将是
prefix_a
、prefix_c
等...您正在做的是生成一个全新的密钥,即prefix_prefix_a
、prefix_prefix_c
等...除非您正在做更复杂的事情,否则您可以将整个循环替换为
You're looping over the array keys already, so if you've got
Then $keys will be
prefix_a
,prefix_c
, etc... What you're doing is generating an entirely NEW key, which'd beprefix_prefix_a
,prefix_prefix_c
, etc...Unless you're doing something more complicated, you could just replace the whole loop with
我相信这应该有效:
I believe this should work: