我有一个函数可以减少(优化)它所拥有的代码行数。这个函数有一些重复的片段。
可以使用 lambda 函数减少此代码吗?
这是我的功能代码:
static function get_all_category_with_widgets( $status = 'all' ) {
$all_categories = SB_Central::get_categories();
$all_widgets = SB_Settings::get_sb_widgets(); // Get all widgets from options variable.
foreach ( $all_categories as $category_key => $category_value ) {
foreach ( $all_widgets as $widget_value ) {
// Create one widget
$widget = array_merge($widget_value['widget'], array ( 'id' => $widget_value['id'], 'status' => $widget_value['status']));
// In this case save active and disable.
if ( $status == 'active_and_disable' && ( $widget_value['status'] == 'active' || $widget_value['status'] == 'disable' )) {
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
} elseif ( $status == 'active' && $widget_value['status'] == 'active' ) {
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
} elseif ( $status == 'disable' && $widget_value['status'] == 'disable' ) {
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
} elseif ( $status == 'deleted' && $widget_value['status'] == 'deleted' ) {
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
} elseif ( $status == 'all' ) {
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
}
}
}
return $all_categories;
}
这是我一直重复的代码:
if ( $category_value[ 'category_title' ] == $widget_value[ 'category' ][ 'title' ] ) {
$all_categories[ $category_key ][ 'widgets' ][ ] = $widget; // Save widget
}
如果您知道减少此代码的更好方法,将受到欢迎。