无法解析(然后循环)具有由逗号分隔的多个值的变量

时间:2011-09-23 18:05:16

标签: php loops

我有公司数据库,每个公司只能运送到一定数量的州。我用一个表单管理它们,这个表单发送到所有状态的MySQL字段(用逗号分隔每个状态)。

我在解析字符串时遇到问题,以便在页面加载时检查与状态相关的框

$check ="NY,CA,FL";

function state_list($check) { 
$arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"DC",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa",  'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'PR'=>"Puerto Rico ",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");
foreach($arr as $k => $v){ 
    $checked = ($check == $k) ? ' checked="yes"' : '';
    echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>';
}
}

2 个答案:

答案 0 :(得分:0)

我认为这与你的比较有关。确保$check为大写。如果那个过去那么它必须是传递$check的值的东西。

编辑:你需要做的就是这个......

$ary = explode(",", $check);

foreach($arr as $k => $v) {
    $checked = (in_array($k, $ary)) ? ' checked="yes"' : '';
    echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>';
}

答案 1 :(得分:0)

如果$check以逗号分隔,您可以将字符串分解并将其转换为数组,然后在for循环中,只需检查状态是否在数组中。

$check ="NY,CA,FL";
$arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"DC",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa",  'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'PR'=>"Puerto Rico ",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");

$states = explode(',', $check); 

foreach($arr as $k => $v){ 
    $checked = in_array($k, $states) ? ' checked="yes"' : '';
    echo '<li><input class="checkStates" name="states" type="checkbox" value="'.$k.'"'.$checked.'>'.$v.'</li>';
}