将数组/对象树的键转换为小写
我目前正在优化一个 PHP 应用程序,发现一个函数被调用了大约 10-20k 次,所以我想我应该从那里开始优化:
function keysToLower($obj)
{
if (!is_object($obj) && !is_array($obj))
return $obj;
foreach ($obj as $key => $element) {
$element = keysToLower($element);
if (is_object($obj)) {
$obj->{strtolower($key)} = $element;
if (!ctype_lower($key))
unset($obj->{$key});
} elseif (is_array($obj) && ctype_upper($key)) {
$obj[strtolower($key)] = $element;
unset($obj[$key]);
}
}
return $obj;
}
大部分时间都花在递归调用上(这在 PHP 中相当慢),但是我没有看到任何方法将其转换为循环。我该怎么做?
I am currently optimizing a PHP application and found one function being called around 10-20k times, so I'd thought I'd start optimization there:
function keysToLower($obj)
{
if (!is_object($obj) && !is_array($obj))
return $obj;
foreach ($obj as $key => $element) {
$element = keysToLower($element);
if (is_object($obj)) {
$obj->{strtolower($key)} = $element;
if (!ctype_lower($key))
unset($obj->{$key});
} elseif (is_array($obj) && ctype_upper($key)) {
$obj[strtolower($key)] = $element;
unset($obj[$key]);
}
}
return $obj;
}
Most of the time is spent in recursive calls (which are quite slow in PHP), but I don't see any way to convert it to a loop. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Foreach
使用随后遍历的内部副本。尝试不使用:或使用引用来避免使用副本:
Foreach
is using an internal copy that is then traversed. Try it without:Or use references to avoid that a copy is used:
您可能还想查找 array_change_key_case()。
对于对象,您可以执行以下操作:
($obj)array_change_key_case((arr)$o)
You might also want to lookup array_change_key_case().
For objects, you can do:
($obj)array_change_key_case((arr)$o)
我假设你不关心转换为数组......
I assume you don't care about casting to array...
这里是一个使用 lambda 的例子:
here a example using lambda:
对旧线程的一些迟到的响应,但是,有一个本机函数可以执行此操作,您可以沿着这些线路将其包装起来。
A some what late response to a old thread but, there's a native function that does this, you could wrap it up something along these lines.
这是一个递归函数,它通过引用进行修改以替换可能包含任何嵌套数组或对象的数组或对象结构中的所有键/属性。它会为每个级别创建一个副本,并在完成更改所有键后覆盖该级别。
代码:(演示)
Here is a recursive function which modifies by reference to replace all keys/properties in an array or object structure that may contain any nested arrays or objects. It makes a copy of each level and overwrites the level after it is finished changing all keys.
Code: (Demo)