0
나는이 코드 행의 양을 줄이기 (최적화)하는 함수가 있습니다. 이 함수에는 반복되는 일부 조각이 있습니다.람다 함수를 사용하여 함수 코드 줄이기
람다 함수를 사용하여이 코드를 줄일 수 있습니까?
이 제 기능 코드 :
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
}
당신은 환영합니다이 코드를 줄일 수있는 더 좋은 방법을 알고 있다면.
모든 것은'IF'의 모든 하나로 그룹화 할 수 있습니다 IF 문/ELSEIF/ELSEIF .... 차단합니다. –
왜 "적은 수의 줄"이 항상 "최적화"와 관련이 있다고 생각하는지 설명하십시오. –
@lightness Racess, 그것은 다른 관점에서 선의 양을 줄일 수 있다는 반복 된 말을하는 인상을줍니다. 어쩌면 잘 해석 할 수도 있지만, 가능한 경우 라인 수를 줄이는 가능성을 확인하는 것이 좋습니다. 모든 것에 감사드립니다. –