首页 > 解决方案 > 循环中 array_merge 导致的慢功能

问题描述

我有两个似乎正在减慢 PHP 的函数,我相信这与在循环中使用 array_merge 有关,只是我在努力弄清楚如何才能不这样做。

function fuseOzone($field) {
    global $ozone;
    if(isset($ozone['all'])) {
        foreach($ozone['all'] as $priority => $functions) {
            if(isset($ozone[$field][$priority])) {
                $ozone[$field][$priority] = array_merge($ozone['all'][$priority], $ozone[$field][$priority]);
            } else {
                $ozone[$field][$priority] = array_merge($ozone['all'][$priority], array());
                $ozone[$field][$priority] = array_unique($ozone[$field][$priority]);
            }
        }
    }
    if(isset($ozone[$field])) {
        ksort($ozone[$field]);
    }
}
function applyOzone($field, $content) {
    global $ozone;
    fuseOzone($field);
    $args = array_slice(func_get_args(), 2);
    if(isset($ozone[$field])) {
        foreach($ozone[$field] as $priority => $functions) {
            if(!is_null($functions)) {
                foreach($functions as $function) {
                    if(!function_exists($function['function'])) {
                        continue;
                    }
                    $all_args = array_merge(array($content), $args);
                    $function_name = $function['function'];
                    $accepted_args = $function['accepted_args'];
                    if($accepted_args === 1) {
                        $the_args = array($content);
                    } elseif($accepted_args > 1) {
                        $the_args = array_slice($all_args, 0, $accepted_args);
                    } elseif($accepted_args === 0) {
                        $the_args = null;
                    } else {
                        $the_args = $all_args;
                    }
                    $content = call_user_func_array($function_name, $the_args);
                }
            }
        }
    }
    return $content;
}

这些函数是一个更大的类的一部分,它本质上与 Wordpress 操作很相似。即我可以通过过滤或类似的方式连接到一部分内容。

标签: phpfilterarray-merge

解决方案


推荐阅读