如何删除数组键中的前缀
我尝试删除数组键中的前缀,但每次尝试都失败。我想要实现的是:
拥有: Array ( [attr_Size] => 3 [attr_Colour] => 7 )
获取: Array ( [Size] => 3 [颜色] => 7 )
非常感谢您的帮助...
I try to remove a prefix in array keys and every attempt is failing. What I want to achieve is to:
Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )
To Get: Array ( [Size] => 3 [Colour] => 7 )
Your help will be much appreciated...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
获取方法之一:
Array ( [Size] => 3 [Colour] => 7 )
从您的Having:Array ( [attr_Size] => 3 [attr_Colour] => 7 )
如果您认为键中会有多个下划线,只需将 foreach 中的第一行替换为
list($dummy, $newkey) = 爆炸('attr_', $key);
One of the ways To Get:
Array ( [Size] => 3 [Colour] => 7 )
From yourHaving: Array ( [attr_Size] => 3 [attr_Colour] => 7 )
If you think there'll be multiple underscores in keys just replace first line inside foreach with
list($dummy, $newkey) = explode('attr_', $key);
如果我理解你的问题,你就不必使用
implode()
来得到你想要的。If I understood your question, you don't have to use
implode()
to get what you want.因为您想要在每个键中保留的第一个字符以大写字母开头,所以您可以简单地向左修剪小写字母和下划线,瞧。要创建所有小写字母和下划线的“掩码”,您可以使用
a..z_
,但由于attr_
是已知前缀,_art 就可以了。诚然,我的代码片段非常适合询问者的示例数据,不会调用
explode()
来创建临时数组,并且每次迭代不会进行多个函数调用。有争议地使用。代码:(演示)
输出:
Because the first character that you'd like to retain in each key starts with an uppercase letter, you can simply left-trim lowercase letters and underscores and voila. To create a "mask" of all lowercase letters and the underscore, you could use
a..z_
, but becauseattr_
is the known prefix,_art
will do. My snippet, admittedly, is narrowly suited to the asker's sample data, does not callexplode()
to create a temporary array, and does not make multiple function calls per iteration. Use contentiously.Code: (Demo)
Output: