php混合foreach和返回重复

时间:2017-12-16 17:51:25

标签: php

以下是 code ,您可以使用 this html输出运行此功能。我有一个数组(多个选择选项),我想将selected="selected"添加到与$districts数组相等的数组。所以我写一个foreach数组到字符串(选择选项)然后一个for循环爆炸$districts

foreach ($readJson as $key => $value){
    if($city == $value["cityid"]){
        for ($i=0; $i<$length; $i++) {
            if($districts[$i] == $value["id"]){
                $selected = "selected='selected'";
            } else {
                $selected = "";
                //break 2;
            }
            echo "<option ".$selected." value='".$value["id"]."'>".$value["title"]."</option>";
        }
    }
}

Selected="selected"工作正常,但问题首先在for循环中再次重复,我不知道如何停止重复项目,只使用break但没有成功。请参阅 ideone 中的完整代码,我做错了什么?

我的目标是在html中实现此结果:

&#13;
&#13;
<select name="Select-District[]" multiple="multiple">
<option selected="selected" value="1">test1</option>
<option selected="selected" value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
</select>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您需要in_array而不是再次循环播放。

foreach ($readJson as $key => $value){
    if($city == $value["cityid"]){
        if(in_array($value["id"], $districts)){
            $selected = "selected='selected'";
        } else {
            $selected = "";
        }
        echo "<option ".$selected." value='".$value["id"]."'>".$value["title"]."</option>";
    }
}

答案 1 :(得分:0)

我修改了你的代码,我想它的工作原理。

<?php

    $readJson = array(
        0 => array(
            'id' => 1,
            'title' => 'test1',
            'cityid' => 1
        ),
        1 => array(
            'id' => 2,
            'title' => 'test2',
            'cityid' => 1
        ),
        2 => array(
            'id' => 3,
            'title' => 'test3',
            'cityid' => 1
        ),
        3 => array(
            'id' => 4,
            'title' => 'test4',
            'cityid' => 1
        ),
        4 => array(
            'id' => 5,
            'title' => 'test5',
            'cityid' => 1
        )
    );

    $city = 1;
    $districts = explode(',' , '2,1');
    $length = sizeof($districts);

    echo "<select name='Select-District[]' multiple='multiple'>";

    $printed = array();

    foreach ($readJson as $key => $value)
    {
        if($city == $value["cityid"])
        {
            if(in_array($value["id"], $districts))
                $selected = "selected='selected'";
            else 
                $selected = "";

            echo "<option ".$selected." value='".$value["id"]."'>".$value["title"]."</option>";          
        }
    }
    echo "</select>";

?>

希望它有效。