Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

php - Using a switch statement to append classname on dropdown

So I have a menu that I converted over to a mega menu and it works great, but I wanted to clean the code up a bit and get some input from professionals here.

Here is the PHP code:

<?php $count = count($sub_items);
$parent_columns = "columns";
$child_column = "column";
switch ($count) {
    case 1:
    case 2:
    case 3:
        $parent_columns .= " is-justify-content-center";
        $child_column .= " is-one-quarter";
        break;
    default:
        $parent_columns .= " is-multiline";
        $child_column = ($count >= 4) ? " column is-one-quarter" : " column";
} ?>
  • The variable $sub_items returns an array and I grab the count using count().
  • Then I base the parent and child variables on cases, 1-3 are the same, while 4+ is different classes.

Then I pull them inside my <div> like this:

<div class="<?= $parent_columns ?>"></div>
<div class="<?= $child_column; ?>"></div>

Does anyone know a better method with my PHP code? Are there other better methods than a switch statement? All help would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of multiple cases you can try this.

<?php
$count = count($sub_items);
$parent_columns = "columns";
$child_column = "column";
if($count <= 3) {
    $parent_columns .= " is-justify-content-center";
    $child_column .= " is-one-quarter";
} else {
    $parent_columns .= " is-multiline";
    $child_column = ($count >= 4) ? " column is-one-quarter" : " column";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...