如何简化此PHP脚本?

时间:2016-10-13 03:24:16

标签: php

我想添加"已选择"属性到组合框。这是我的PHP:

monday, tuesday

我可能有超过数百个IF。

我试过这个,但似乎没有用:

if($results['status'] == 1)
{ $ok1= "selected"; }
else
{ $ok1= ""; }

if($results['status'] == 2)
{ $ok2= "selected"; }
else
{ $ok2= ""; }

if($results['status'] == 3)
{ $ok3= "selected"; }
else
{ $ok3= ""; }

if($results['status'] == 4)
{ $ok4= "selected"; }
else
{ $ok4= ""; }

我想尽可能简单。也许是1或2行。因为我有很多应该这样对待的组合框

编辑(我的组合框):

for($a=1; $a<=4; $a++){
    if($results['status'] == $a)
    { $ok = "selected"; }
    else
    { $ok = ""; }

}

5 个答案:

答案 0 :(得分:0)

你可以这样做,

<?php

// status list array
$selectValues = array(1, 2, 3, 4);

echo '<select name="combo_name">';
foreach($selectValues  as $value){
    $selected = "";
    if($results['status'] == $value){
        $selected = ' selected="selected" ';
    }
    echo '<option '.$selected.' value="'.$value.'">'.$value.'</option>';
}
echo '</select>';  

?>

答案 1 :(得分:0)

由于$results['status']只能有1个值,因此请使用动态变量名称让您的生活轻松!

// initialize all 4 to blank
for($a=1; $a<=4; $a++){
    ${"ok" . $a} = "";
}
// set the one that is selected 
${"ok" . $results['status']} = "selected";

这个答案非常具有可扩展性,您只需更改&#34; for&#34;从4到1000的行,它没有添加额外的代码。

答案 2 :(得分:0)

你所要做的就是制作一个数组并循环遍历它 -

Spinner s, s1;
    Button ok;
    Object _globalString, _globalString2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        s = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner);
        s.setAdapter(adapter);

        s1 = (Spinner) findViewById(R.id.spinner01);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, array_spinner01);
        s1.setAdapter(adapter1);
//
//    s2=(Spinner)findViewById(R.id.spinner02);
//    ArrayAdapter<String> adapter2=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_dropdown_item,array_spinner02);
//    s2.setAdapter(adapter2);

        ok = (Button) findViewById(R.id.btn_ok);
        ok.setOnClickListener(this);

        s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                _globalString = parent.getItemAtPosition(position);
            }

            //@Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

        s1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                _globalString2 = parent.getItemAtPosition(position);
            }

            // @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_ok) {
            if (_globalString.equals("Honda") || _globalString2.equals("Civic")) {
                startActivity(new Intent(getApplicationContext(), Civic.class));
            } else if (_globalString.equals("Toyota") || _globalString2.equals("Gli")) {
                startActivity(new Intent(getApplicationContext(), Toyota.class));
            }

        }
    }
}

您需要在组合框中每次检查所选值。

答案 3 :(得分:0)

希望这有帮助

$ combolength - 组合中的选项数

$ok = array_fill(0, $combolength - 1, '');
switch ($results['status']) {
    case $results['status']:
        $ok[$results['status']]= 'selected';
        break;
} 

答案 4 :(得分:0)

我个人认为“简化”你已经拥有的东西不是解决这个问题的方法。如果您没有使用框架,我认为您应该考虑如何使您的脚本可重用,特别是因为您说“我有许多应该这样对待的组合框。“不使用像函数/方法这样的包含元素听起来像是从硬编码的角度来看很多额外的工作。我个人会创建一个类,您可以使表单字段标准化,并且您可以使用动态键/值数组提供数组。简单的例子:

<强> /core/classes/Form.php

class Form
    {
        # The idea here is that you would have many methods to build form fields

        # You can edit this as you please
        public function select($settings)
            {
                $class      =   (!empty($settings['class']))? ' class="'.$settings['class'].'"':'';
                $id         =   (!empty($settings['id']))? ' id="'.$settings['id'].'"':'';
                $selected   =   (!empty($settings['selected']))? $settings['selected']:false;
                $other      =   (!empty($settings['other']))? ' '.implode(' ',$settings['other']):'';
                ob_start();
            ?>
<select name="<?php echo $settings['name']; ?>"<?php echo $other.$id.$class; ?>>
    <?php foreach($settings['options'] as $key => $value) { ?>
    <option value="<?php echo $key; ?>"<?php if($selected == $key) echo ' selected'; ?>><?php echo $value; ?></option>
    <?php } ?>
</select>
            <?php
                $data = ob_get_contents();
                ob_end_clean();
                return $data;
            }
    }

使用:

# Include the class
require_once(__DIR__.'/core/classes/Form.php');
# You can use $form = new Form(); echo $form->select(...etc.
# but I am just doing this way for demonstration
echo (new Form())->select(array(
    'name'=>'status',
    'class'=>'classes here',
    'id'=>'select1',
    'other'=>array(
        'data-instructions=\'{"stuff":["things"]}\'',
        'onchange="this.style.borderColor=\'red\';this.style.fontSize=\'30px\'"'
    ),
    # Options can be assign database returned arrays
    'options'=>array(
        '_'=>'Select',
        1=>'A',
        2=>'B',
        3=>'C',
        4=>'D'
    ),
    'selected'=>((!empty($results['status']))? $results['status'] : '_')
    ));

给你:

<select name="status" data-instructions='{"stuff":["things"]}' onchange="this.style.borderColor='red';this.style.fontSize='30px'" id="select1" class="classes here">
    <option value="_">Select</option>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select>